0

I have a Servlet that uploads an image, and saves the path in a MySQL db. I use the same code for another image upload on a different jsp page, and I get a null pointer exception on "getFileName();"

I do not see any difference in this code. Please help:

addlientimage.java

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, ClassNotFoundException, SQLException {
        response.setContentType("text/html;charset=UTF-8");

        String name = request.getParameter("clientname");
        String id = request.getParameter("clientid");
        String password = request.getParameter("clientpassword");
        String email = request.getParameter("clientemail");

        final String path = getServletContext().getRealPath("/imgs");
        final Part filePart = request.getPart("imageurl");
        final String fileName = getFileName(filePart);
        String url = "imgs/" + fileName;

        OutputStream outStream;
        outStream = null;
        InputStream filecontent = null;
        final PrintWriter writer = response.getWriter();
        response.sendRedirect("clients.jsp");

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

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

            while ((read = filecontent.read(bytes)) != -1) {
                outStream.write(bytes, 0, read);
            }
            Mysqlconnector dbconnect = new Mysqlconnector();
            /* TODO output your page here. You may use following sample code. */
            try (PreparedStatement clientinfo = dbconnect.getConnection().prepareStatement("INSERT INTO clients VALUES ( ?, ?, ?, ?, ? )")) {
                clientinfo.setString(1, id);
                //setting the first placeholder to the password recieved from the client
                clientinfo.setString(2, password);
                clientinfo.setString(3, name);
                clientinfo.setString(4, url);
                clientinfo.setString(5, email);

                clientinfo.executeUpdate();

                String clients = new PopulateClientsTable().getClientRows();

                HttpSession session = request.getSession();
                session.setAttribute("clients", clients);

            }

        } 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());

        } finally {
            if (outStream != null) {
                outStream.close();
            }
            if (filecontent != null) {
                filecontent.close();
            }
            if (writer != null) {
                writer.close();
            }
        }
    }

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

addmanager.java

response.setContentType("text/html;charset=UTF-8");

    String personName = request.getParameter("mediapersonname");
    String productName = request.getParameter("productname");
    String mediainfoid = request.getParameter("mediainfoid");
    String mediaAbout = request.getParameter("mediaabout");
    String personAbout = request.getParameter("personabout");
    String productAbout = request.getParameter("productabout");

    final String path = getServletContext().getRealPath("/imgs");
    final Part filePart = request.getPart("personurl");
    final String fileName = getFileName(filePart);
    String url = "imgs/" + fileName;

    OutputStream outStream;
    outStream = null;
    InputStream filecontent = null;
    final PrintWriter writer = response.getWriter();
    response.sendRedirect("adminmediainfo.jsp");

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

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

        while ((read = filecontent.read(bytes)) != -1) {
            outStream.write(bytes, 0, read);
        }

        Mysqlconnector dbconnect = new Mysqlconnector();
        /* TODO output your page here. You may use following sample code. */
        try (PreparedStatement clientinfo = dbconnect.getConnection().prepareStatement("INSERT INTO mediainfo VALUES ( ?, ?, ?, ?, ?, ?, ? )")) {
            //setting the first placeholder to the password recieved from the client
            clientinfo.setString(1, mediainfoid);
            clientinfo.setString(2, mediaAbout);
            clientinfo.setString(3, personName);
            clientinfo.setString(4, productName);
            clientinfo.setString(5, productAbout);
            clientinfo.setString(6, personAbout);
            clientinfo.setString(7, url);

            clientinfo.executeUpdate();

            String clients = new PopulateMediaInfoTable().getClientRows();

            HttpSession session = request.getSession();
            session.setAttribute("mediainfo", clients);

        }

    } 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());

    } finally {
        if (outStream != null) {
            outStream.close();
        }
        if (filecontent != null) {
            filecontent.close();
        }
        if (writer != null) {
            writer.close();
        }
    }
}

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

The code for addclientimage.java works. The code for addmanager.java does not.


ERROR LOG

type Exception report

message

description The server encountered an internal error that prevented it from fulfilling this request.

exception

java.lang.NullPointerException
    AddMediaInfo.getFileName(AddMediaInfo.java:115)
    AddMediaInfo.processRequest(AddMediaInfo.java:53)
    AddMediaInfo.doPost(AddMediaInfo.java:158)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
note The full stack trace of the root cause is available in the Apache Tomcat/8.0.15 logs.
TejjD
  • 2,571
  • 1
  • 17
  • 37

1 Answers1

0

I find just two possible reasons for getFileName to throw a NPE:

final String partHeader = part.getHeader("content-disposition");
for (String content : part.getHeader("content-disposition").split(";")) {
  • Either part is null, so you have to ensure that the caller method is not passing a null to getFileName. I.E.: There exists a "personurl" part within the input request.
  • Wither partHeader is null, so you have to ensure that the client is actually including a "content-disposition" header within the sent request.
Little Santi
  • 8,563
  • 2
  • 18
  • 46