FileUploadServlet даже не вызывается - PullRequest
0 голосов
/ 06 августа 2020

Я пытаюсь запустить образец для загрузки файлов из веб-приложения с помощью NetBeans

Весь проект состоит всего из четырех файлов.

  1. файловая сеть. xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <servlet>
        <servlet-name>upload</servlet-name>
        <servlet-class>servlets.FileUploadServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>upload</servlet-name>
        <url-pattern>/upload</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>
индекс файла. html
<!DOCTYPE html>
<html lang="en">
    <head>
        <title>File Upload</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
        <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
        <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
        <script type ="text/javascript" src="index.js"></script>        
    </head>
    <body>
        File:
        <input type="file" name="file" id="file" /> <br/>
        Destination:
        <input type="text" value="/tmp" name="destination"/>
        </br>
        <button value="Upload" name="upload" id="upload">Upload</button>
        <p id=msg></p>
    </body>
</html>
индекс файла. js
$(document).ready(function () {
    
    $("#upload").click( function () {
            $.post("upload",{}, function() {
                $("#msg").html("hola");
            });        
    });
});

И 4. FileUploadServlet. java, в котором импорт опущен.

@MultipartConfig
public class FileUploadServlet extends HttpServlet {

    private final static Logger LOGGER = 
            Logger.getLogger(FileUploadServlet.class.getCanonicalName());    
    
    protected void processRequest(HttpServletRequest request,
           HttpServletResponse response)
           throws ServletException, IOException {
       response.setContentType("text/html;charset=UTF-8");

       // Create path components to save the file
       final String path = request.getParameter("destination");
       final Part filePart = request.getPart("file");
       final String fileName = getFileName(filePart);

       OutputStream out = null;
       InputStream filecontent = null;
       final PrintWriter writer = response.getWriter();

       try {
           out = new FileOutputStream(new File(path + File.separator
                   + fileName));
           filecontent = filePart.getInputStream();

           int read;
           final byte[] bytes = new byte[1024];

           while ((read = filecontent.read(bytes)) != -1) {
               out.write(bytes, 0, read);
           }
           writer.println("New file " + fileName + " created at " + path);
           LOGGER.log(Level.INFO, "File{0}being uploaded to {1}", 
                   new Object[]{fileName, path});
       } catch (FileNotFoundException fne) {
           writer.println("You either did not specify a file to upload or are "
                   + "trying to upload a file to a protected or nonexistent "
                   + "location.");
           writer.println("<br/> ERROR: " + fne.getMessage());

           LOGGER.log(Level.SEVERE, "Problems during file upload. Error: {0}", 
                   new Object[]{fne.getMessage()});
       } finally {
           if (out != null) {
               out.close();
           }
           if (filecontent != null) {
               filecontent.close();
           }
           if (writer != null) {
               writer.close();
           }
       }
   }

    private String getFileName(final Part part) {
        final String partHeader = part.getHeader("content-disposition");
        LOGGER.log(Level.INFO, "Part Header = {0}", partHeader);
        for (String content : part.getHeader("content-disposition").split(";")) {
            if (content.trim().startsWith("filename")) {
                return content.substring(
                        content.indexOf('=') + 1).trim().replace("\"", "");
            }
        }
        return null;
    }
}

И после сборки установив точку останова в отладчике FF, можно увидеть, что сервлет вызывается, но выполнение не останавливается на точке останова, установленной в IDE NetBeans, первой строке сервлета.

Может ли кто-нибудь объяснить мне, что я неправильно делаете?

Спасибо за вашу помощь!

Карлес

...