0

I'm doing a web server as a part of an online shop application, and I'm trying to make a form jsp page work. I'm using Eclipse IDE with Maven, and Jetty plugin to try it.

It goes like this:

From the index.jsp welcome page the user press a button with submits a GET request to AddProductoServlet. This is necessary lo load a list of "tiendas"(shops) and past it to the jsp page, so the user can choose one from a drop-down list (select html element)

Here is the GET method in AddProductoServlet:

@Override
public void doGet(HttpServletRequest request,
                HttpServletResponse response)
    throws ServletException, IOException {

    logger.debug("doGet de AddProductoServlet");

    // llamada al servicio para pedir la lista de tiendas en la BD
    // TODO añadir metodo a la clase conversora para meter listas de tiendas
    //List<TiendaWTO> tiendaWTOs = TiendaTOtoTiendaWTOConversor.toTiendaWTO(productoService.getTiendas());

    // Test
    List<String> tiendaWTOs = new ArrayList<String>();
    tiendaWTOs.add("El Rincón de José");
    tiendaWTOs.add("El bar de Antonio");
    tiendaWTOs.add("Pezuñita comics");

    request.setAttribute("tiendas", tiendaWTOs);

    // TODO lo que viene a continuacion en el ejemplo de servjsptutorial
    // va en una clase aparte y se llama a la función forwardTo
    RequestDispatcher requestDispatcher = request.getRequestDispatcher("AddProducto.jsp");

    requestDispatcher.forward(request, response);
}

And here the jsp page AddProducto:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"
    import="java.util.Map,
        java.util.List" %>

<html>
<head>
    <title>Nosa Tenda - Crear producto</title>
</head>

<body text="#000000" bgcolor="#ffffff">

<%-- Get errors. --%>

<%
    String nombreErrorMessage = "";
    String imagenErrorMessage = "";
    String precioErrorMessage = "";
    String stockErrorMessage = "";
    String tiendaErrorMessage = "";

    Map<String, String> errors = (Map<String, String>) request.getAttribute("errors");



    if (errors != null) {

        String errorHeader = "<font color=\"red\"><b>";
        String errorFooter = "</b></font>";

        if (errors.containsKey("nombre")) {
            nombreErrorMessage = errorHeader + errors.get("nombre") + 
                errorFooter;
        }

        if (errors.containsKey("imagen")) {
            imagenErrorMessage = errorHeader + errors.get("imagen") + 
                errorFooter;
        }

        if (errors.containsKey("precio")) {
            precioErrorMessage = errorHeader + errors.get("precio") + 
                errorFooter;
        }

        if (errors.containsKey("stock")) {
            stockErrorMessage = errorHeader + errors.get("stock") + 
                errorFooter;
        }

        if (errors.containsKey("tienda")) {
            tiendaErrorMessage = errorHeader + errors.get("tienda") + 
                errorFooter;
        }

    }

    String nombre = request.getParameter("nombre");
    if (nombre==null) {
        nombre="";
    }
    String descripcion = request.getParameter("descripcion");
    if (descripcion==null) {
        descripcion="";
    }
    String imagen = request.getParameter("imagen");
    if (imagen==null) {
        imagen="";
    }
    String precio = request.getParameter("precio");
    if (precio==null) {
        precio="";
    }
    String stock = request.getParameter("stock");
    if (stock==null) {
        stock="";
    }

    List<String> tiendas = (List<String>) request.getAttribute("tiendas");

    //response.setContentType("charset=UTF-8");
%>  

<div align="center">
    <p>
        <font color="#000099" face="Arial, Helvetica, san-serif">
            <b>Crear producto</b>
        </font>
    </p>
</div>

<form method="POST" action="AddProducto">

<table width="100%" border="0" align="center" cellspacing="12">

<%-- Nombre --%>

    <tr>        
        <th align="right" width="50%">
            Nombre 
        </th>
        <td align="left">   
            <input type="text" name="nombre" 
                value="<%= nombre %>"
                size="64" maxlength="100">
            <%= nombreErrorMessage %>
        </td>
    </tr>

<%-- Descripcion --%>

    <tr>        
        <th align="right" width="50%">
            Descripción 
        </th>
        <td align="left">   
            <textarea name="descripcion" 
                rows="8" cols="40" maxlength="450"><%= descripcion %></textarea>
        </td>
    </tr>

<%-- Imagen --%>

    <tr>        
        <th align="right" width="50%">
            URL de la imagen 
        </th>
        <td align="left">   
            <textarea name="imagen" 
                rows="8" cols="40" maxlength="450"><%= imagen %></textarea>
            <%= imagenErrorMessage %>
        </td>
    </tr>

<%-- Precio --%>

    <tr>        
        <th align="right" width="50%">
            Precio 
        </th>
        <td align="left">   
            <input type="text" name="precio" 
                value="<%= precio %>"
                size="9" maxlength="8">
            <%= precioErrorMessage %>
        </td>
    </tr>

<%-- Stock --%>

    <tr>        
        <th align="right" width="50%">
            Stock 
        </th>
        <td align="left">   
            <input type="text" name="stock" 
                value="<%= stock %>"
                size="9" maxlength="8">
            <%= stockErrorMessage %>
        </td>
    </tr>

<%-- Tienda --%>

    <tr>        
        <th align="right" width="50%">
            Tienda 
        </th>
        <td align="left">   
            <select name="tiendaId">
            <% for (int i=0; i < tiendas.size(); i++) { %>
            <option value="<%= tiendas.get(i) %>"><%= tiendas.get(i) %></option>
            <% } %>
            </select>
            <%= tiendaErrorMessage %>
        </td>
    </tr>

<%-- Create button --%>

    <tr>        
        <td width="50%"></td>
        <td align="left" width="50%">
            <input type="submit" value="Crear producto">
        </td>
    </tr>

</table>

</form>


</body>

</html>

Till here everything works just fine, page loads and the drop-down list is correctly filled. Notice that right now I'm using a mock to load the shop names, later there will be a call to the service between the web service and the database, but that's not important now.

Now, what I'm trying to do next when the user presses the submit button of the form is to call the post method of AddProductoServlet and check the form fields: if there are no errors, it redirects to a success page. I have tested it, it works, and from the debug I know that all parameters are passed to the servlet correctly:

response.sendRedirect("AddProductoExito.jsp?id="
                + 1);

Problem comes when there is any mistake and this line is called:

requestDispatcher.forward(request, response);

Here is the whole doPost method:

@Override
public void doPost(HttpServletRequest request,
                HttpServletResponse response)
    throws ServletException, IOException {

    logger.debug("doPost de AddProductoServlet");

    Map<String, String> errors = new HashMap<String, String>();

    String nombre = request.getParameter("nombre");
    String descripcion = request.getParameter("descripcion");
    String imagen = request.getParameter("imagen");
    String precio = request.getParameter("precio");
    String stock = request.getParameter("stock");
    //Long tiendaId = Long.parseLong(request.getParameter("tiendaId"));
    String tiendaId = request.getParameter("tiendaId");

    // validamos campos
    PropertyValidator.validateMandatory(errors, "nombre", nombre);
    PropertyValidator.validateMandatory(errors, "imagen", imagen);
    double precioAsDouble = PropertyValidator.validateDouble(errors,
            "precio", precio, true, 0, Double.MAX_VALUE);
    long stockAsLong = PropertyValidator.validateLong(errors,
            "stock", stock, true, 0, Long.MAX_VALUE);
    /*long tiendaIdAsLong = PropertyValidator.validateLong(errors,
            "tiendaId", tiendaId, true, 0, Long.MAX_VALUE);*/

    if (!errors.isEmpty()) {
        request.setAttribute("errors", errors);
        // TODO lo que viene a continuacion en el ejemplo de servjsptutorial
        // va en una clase aparte y se llama a la función forwardTo
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("AddProducto.jsp");

        requestDispatcher.forward(request, response);
    } else {

        // llamada al servicio para insertar producto
        // TODO usar productoWTO (meter clase conversora en la linea siguiente)
        /*ProductoTO insertedProducto = productoService.newProducto(
                                            nombre,
                                            descripcion,
                                            imagen,
                                            precio,
                                            stock,
                                            tiendaId);

        response.sendRedirect("AddProductoExito.jsp?id="
                + insertedProducto.getId());*/

        // Test
        response.sendRedirect("AddProductoExito.jsp?id="
                + 1);
    }

The objective of all this will be to load again AddProducto.jsp in case of error, but this time showing the errors on screen (some red text next to the field that has an error indicating the problem), and also showing whatever was filled in the text fields previously.

Here is the stacktrace of the NullPointerException error I get. Line 85 of AddProductoServlet which is mentioned corresponds to 'requestDispatcher.forward(request, response);' as I mentioned before:

2015-01-29 12:01:24.877:WARN:oejs.ServletHandler:
org.apache.jasper.JasperException: java.lang.NullPointerException
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:492)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:378)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:684)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:503)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:137)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:575)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:231)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1086)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:429)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:193)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1020)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:135)
    at org.eclipse.jetty.server.Dispatcher.forward(Dispatcher.java:276)
    at org.eclipse.jetty.server.Dispatcher.forward(Dispatcher.java:103)
    at es.udc.jcastedo.NosaTenda.webservice.service.web.servlets.AddProductoServlet.doPost(AddProductoServlet.java:85)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:755)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:684)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:503)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:137)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:557)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:231)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1086)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:429)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:193)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1020)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:135)
    at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:255)
    at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:154)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116)
    at org.eclipse.jetty.server.Server.handle(Server.java:370)
    at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:494)
    at org.eclipse.jetty.server.AbstractHttpConnection.content(AbstractHttpConnection.java:982)
    at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.content(AbstractHttpConnection.java:1043)
    at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:865)
    at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:240)
    at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:82)
    at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:696)
    at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:53)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:608)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:543)
    at java.lang.Thread.run(Thread.java:695)
Caused by: 
java.lang.NullPointerException
    at org.apache.jsp.AddProducto_jsp._jspService(AddProducto_jsp.java from :233)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:111)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:403)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:492)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:378)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:684)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:503)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:137)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:575)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:231)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1086)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:429)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:193)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1020)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:135)
    at org.eclipse.jetty.server.Dispatcher.forward(Dispatcher.java:276)
    at org.eclipse.jetty.server.Dispatcher.forward(Dispatcher.java:103)
    at es.udc.jcastedo.NosaTenda.webservice.service.web.servlets.AddProductoServlet.doPost(AddProductoServlet.java:85)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:755)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:684)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:503)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:137)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:557)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:231)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1086)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:429)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:193)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1020)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:135)
    at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:255)
    at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:154)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116)
    at org.eclipse.jetty.server.Server.handle(Server.java:370)
    at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:494)
    at org.eclipse.jetty.server.AbstractHttpConnection.content(AbstractHttpConnection.java:982)
    at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.content(AbstractHttpConnection.java:1043)
    at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:865)
    at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:240)
    at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:82)
    at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:696)
    at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:53)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:608)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:543)
    at java.lang.Thread.run(Thread.java:695)
2015-01-29 12:01:24.880:WARN:oejs.ServletHandler:/NosaTenda-webservice/AddProducto
java.lang.NullPointerException
    at org.apache.jsp.AddProducto_jsp._jspService(AddProducto_jsp.java from :233)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:111)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:403)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:492)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:378)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:684)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:503)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:137)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:575)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:231)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1086)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:429)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:193)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1020)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:135)
    at org.eclipse.jetty.server.Dispatcher.forward(Dispatcher.java:276)
    at org.eclipse.jetty.server.Dispatcher.forward(Dispatcher.java:103)
    at es.udc.jcastedo.NosaTenda.webservice.service.web.servlets.AddProductoServlet.doPost(AddProductoServlet.java:85)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:755)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:684)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:503)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:137)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:557)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:231)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1086)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:429)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:193)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1020)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:135)
    at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:255)
    at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:154)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116)
    at org.eclipse.jetty.server.Server.handle(Server.java:370)
    at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:494)
    at org.eclipse.jetty.server.AbstractHttpConnection.content(AbstractHttpConnection.java:982)
    at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.content(AbstractHttpConnection.java:1043)
    at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:865)
    at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:240)
    at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:82)
    at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:696)
    at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:53)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:608)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:543)
    at java.lang.Thread.run(Thread.java:695)

So now I'm stuck. Don't know why that error is happening. The call is the same that in the GET method, which works just fine.

I have debugged it and the path is correct, same as before. Nevertheless I have tried several combinations, as it seems it can't find the jsp page for some reason, like /AddProducto.jsp and others, to no avail.

I have also done a research on similar questions, in this page and others, but nothing. Configuration seems fine, as all the other servlets work just fine.

What am I missing here? Thanks.

Julio Castedo
  • 21
  • 1
  • 2
  • 8

1 Answers1

0

Talk about overcomplicating things... here I was thinking something was off about the two consecutive calls to the same page by the doGet and the doPost, that maybe the response or the request might had got an attribute corrupted or something, or even worse the config was buggy... nope, as usual was something way more simple and way more obvious, once you notice it of course.

To simply put it, the "tiendas" reference is not made again in the doPost, since for some reason I thought it was still attached to the request. So when the jsp page tried to do the "tiendas.get(i)", obviously it didn't find the variable and a NullPointerException was thrown.

It's also because I'm lacking at debugging pages that I was focused on the servlets and didn't thought the exception was actually thrown by the page.

Thanks and sorry to anyone who invested time on this, my mistake.

Julio Castedo
  • 21
  • 1
  • 2
  • 8