0

I have a problem when retrieving data (an Integer value) between servlets, when I want to multiply the value retrieved. I have this function in my first servlet,

        private int totalNumberOf(Map<String,Integer> cart) {
    int counter = 0;

    for (String key : cart.keySet())
        counter += cart.get(key);

    return counter;
}

And I also have the attribute for it (placed at the end of the doGet() method)...

        req.setAttribute("quantity", new Integer(totalNumberOf(cart)));

, a function that gives me the total number of products that are in the cart, which updates the value every time I add something to the cart so when I finish buying I can get an updated value of the number of products that are currently in the cart.

The problem comes now, when I try to do the fictional checkout (because I just have a generic price for every type of product) and I have to multiply the number of items by the generic price (here's where the NullPointer shows up).

Here's the code of my second servlet,

@Override
public void doGet(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {

    HttpSession session = req.getSession();

    Integer quantity;
    int toPay;
    int genericValue = 20;

    quantity = (Integer) req.getAttribute("quantity");

    toPay = quantity.intValue() * genericValue; // NullPointer

}

I've tried everything in every way but I can't get rid of that ugly NullPointer. Hope you can help me a bit with this...

UPDATE Servlet1

@Override
public void doGet(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {

    String mensajeBienvenida = "";
    Map<String,Integer> carrito = null;

    String articuloElegido = req.getParameter("producto");

    HttpSession session = req.getSession();

    if (session.isNew()) {
        session.invalidate();
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/error.html");
        dispatcher.forward(req, res);
    }
    else {
        String nombreUsuario = ((Usuario)session.getAttribute("user")).getNombre();
        if (session.getAttribute("carrito") == null) {
            carrito = new HashMap<String,Integer>();
            session.setAttribute("carrito",carrito);
            mensajeBienvenida="Bienvenido a la tienda, " + nombreUsuario + "!";
        }
        else {
            carrito = (Map<String,Integer>) session.getAttribute("carrito");
            mensajeBienvenida = "Qué bien que sigas comprando, " + nombreUsuario + "!";
        }
        insertarEnCarrito(carrito, articuloElegido);
    }
    req.setAttribute("mensaje", mensajeBienvenida);
    req.setAttribute("cesta", cestaDeLaCompraEnHTML(carrito));
    req.setAttribute("cantidad", numeroTotalLibros(carrito));
    RequestDispatcher dispatcher = getServletContext().getNamedDispatcher("VistaTienda");
    dispatcher.forward(req, res);

}

@Override
public void doPost(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
        doGet( req,res );
}

private void insertarEnCarrito(Map<String,Integer> carrito, String articulo) {
    if (carrito.get(articulo) == null){
        carrito.put(articulo, new Integer(1));
    }
    else {
        int numeroArticulos = (Integer)carrito.get(articulo).intValue();
        carrito.put(articulo, new Integer(numeroArticulos+1));
    }
}

private String cestaDeLaCompraEnHTML(Map<String,Integer> carrito) {
    String cestaEnHTML = "";

    for (String key : carrito.keySet())
        cestaEnHTML += "<p>["+key+"], "+carrito.get(key)+" unidades</p>";
    return cestaEnHTML;
}

private int numeroTotalLibros(Map<String,Integer> carrito) {
    int counterLibro = 0;

    for (String key : carrito.keySet())
        counterLibro += carrito.get(key);

    return counterLibro;
}

}

Servlet2

@Override
public void doGet(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {

    String mensajeBienvenida;
    String cestaDeLaCompraEnHTML;

    mensajeBienvenida = (String) req.getAttribute("mensaje");
    cestaDeLaCompraEnHTML = (String) req.getAttribute("cesta");

    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    out.println("<HTML>");
    out.println("<HEAD><TITLE>Tienda con login!</TITLE></HEAD>");
    out.println("<BODY>" + mensajeBienvenida + "<br>");
    out.println(cestaDeLaCompraEnHTML + "<br>");
    out.println("PRUEBA CANTIDAD LIBROS EN TOTAL - " + req.getAttribute("cantidad") + "<br>");
    out.println("<a href=\"form.html\">Seguir comprando!</a></BODY></HTML>");
    out.println("<a href=\"login.html\">Anular Compra</a></BODY></HTML>");
    out.println("<a href=\"pagar\">Pagar Compra</a></BODY></HTML>");

}

@Override
public void doPost(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
        doGet( req,res );
}

Servlet3

@Override
public void doGet(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {

    HttpSession session = req.getSession();

    Integer cantidadLibro;
    int pagar;
    int valorLibro = 20;

    Map<String,Integer> carrito = (Map<String,Integer>) session.getAttribute("carrito");
    Usuario usuario = (Usuario) session.getAttribute("user");
    cantidadLibro = (Integer) req.getAttribute("cantidad");

    if (cantidadLibro == null){
        cantidadLibro = 0;
    } else {
        cantidadLibro = (Integer) req.getAttribute("cantidad");
    }

    // pagar = cantidadLibro.intValue() * valorLibro;

    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    out.println("<HTML>");
    out.println("<HEAD><TITLE>Tienda con login!</TITLE></HEAD>");
    out.println("<BODY><p><b>COMPRA REALIZADA!</b><br>");
    out.println("<br><p>Total a pagar por su compra - " + "<br>");
    out.println("<br><p>PRUEBA getAttribute - " + req.getAttribute("cantidad") + "<br>");
    out.println("<br><p>Gracias por su compra " + usuario.getNombre() + " " + usuario.getApellidos() + "<br>");
    out.println("<br><p>e-mail del usuario - " + usuario.getEmail() + "<br>");
    out.println("<br><p>User ID - " + usuario.getId() + "<br>");

    session.invalidate();

}

@Override
public void doPost(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
        doGet( req,res );
}
5
  • 1
    Where do you do req.setAttribute("cantidad", new Integer(numeroTotalLibros(carrito)));? Feb 4, 2015 at 19:46
  • Confirm that req.getAttribute("quantity") actually is giving a value
    – Ascalonian
    Feb 4, 2015 at 19:46
  • req.setAttribute("cantidad", new Integer(numeroTotalLibros(carrito))); is req.setAttribute("quantity", new Integer(totalNumberOf(cart))); Sorry for that. Its placed at the end of the doGet() method. Feb 4, 2015 at 19:47
  • Update the question with that new information please
    – Ascalonian
    Feb 4, 2015 at 19:48
  • With the information you are giving I have reproduced this and it works for me. Can you please provide the full code, without translations for both Servlets, please? Feb 4, 2015 at 22:10

4 Answers 4

0

Besides the refactoring and optimisation that your code might need, the problem you are refering to is that your are setting the attribute "cantidad" to the request instead of the session.

In Servlet1, replace this

req.setAttribute("cantidad", numeroTotalLibros(carrito));

with this

session.setAttribute("cantidad", numeroTotalLibros(carrito));

And in Servlet3, replace this

cantidadLibro = (Integer) req.getAttribute("cantidad");

with this

cantidadLibro = (Integer) session.getAttribute("cantidad");

The reason is that you are forwarding your request from Servlet1 to Servlet2, and so in Servlet2 you can access the "forwarded" request and all its attributes, BUT Serlvet3 is called independently at a later stage. I guess that is when you press "Pagar" in the rendered HTML page. Therefore, you can no longer access those attributes via the request because it is a different request. You can instead access them via the session if you stored them there previously.

Hope this helps.

1
  • Thanks a lot Pedro! I was so obfuscated with the NullPointer that I couldn't even see that the solution was there with the "usuario" variable also! Thanks! Feb 8, 2015 at 23:56
0

Have you ever heard about debugging tools?

Your quantity variable has null value, it could be because of abscense attribute quantity in request. That is why you got NPE: null * (primitive numeric constant) -> NullPointerException.

0

From your code it it looks like "quantity.intValue()" throws your null pointer because quantity is null. Try this:

@Override
public void doGet(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {

HttpSession session = req.getSession();

Integer quantity = 0;
int toPay;
int genericValue = 20;

if (req.getAttribute("quantity") != null) {
  quantity = (Integer) req.getAttribute("quantity");
}


toPay = quantity.intValue() * genericValue; 

}

Notice not only do I initialize quantity with a value of 0 (so that it is not null) I also add a null check to "req.getAttribute("quantity")" so that you do not assign null to quantity in the case where .getAttribute returns null.

0

It's likely that your getAttribute function returned null. Remember to do null checking in code. I suggest a if (quantity != null) check before you call .intValue()

Another possible solution would be to check what .getAttribute() returned instead of checking what quantity was set to. You could also give quantity a default value.

if (req.getAttribute("quantity") == null) {
    quantity = 0;
} else {
    quantity = (Integer) req.getAttribute("quantity");
}
9
  • I've added the null checking code into the servlet and yes, getAttribute returns null, but why, it doesn't even store it? Doesn't the setAttribute method stores whatever Object you pass to it and identifies it with a string you want it to be identified with? Feb 4, 2015 at 20:08
  • Did you confirm that new Integer(totalNumberOf(cart)) is returning the value you expect?
    – Ascalonian
    Feb 4, 2015 at 20:10
  • Yes yes, I've already confirmed that. Another servlet goes after that one, showing the products that I have at the moment in the cart, where I've added a line where the attribute is shown and it is correct. Feb 4, 2015 at 20:16
  • Are you saying that when you print getAttribute, you're getting something back? Print getAttribute(quantity) right after you setAttribute and see what comes back.
    – Aify
    Feb 4, 2015 at 20:28
  • Indeed, I'm getting the int counter of the method in return. Feb 4, 2015 at 20:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.