jspservletsattributesusersession

How to retrieve an session attribute from another servlet?


I have to do a project for college, and i'm having some problems, if any of you could help me i'll be very grateful.

The project it's an used products store, and until now we had to make a servlet for inserting products in a list that later will be saved in a generic user session(we're not using any kind of DB, only user session). That was ok, but now i have to do another servlet that searches in this list, but i'm having problems retrieving the list from the other servlet.

Code for Servlet that saves the products in a user session attribute.

listaProds.add(prod);
request.getSession().setAttribute("listaProdutos", listaProds);

Here's the code where i try to retrieve the list from another servlet

listaProds =(ArrayList<Produto>) request.getSession().getAttribute("listaProdutos");

The thing is, i'm gettin' only a null pointer in the second servlet, and i don't have a clue on what to do next...

Additional Information: i'm using netbeans, both servlets are in the same package, both servlets are 'called' from two different .jsp pages.

If anyone can help me, that'll be great, and if you'll need any other information, just ask and i'll provide.

Thanks in advance!!


Solution

  • You are getting NPE because you are retrieving the object , rather you should try

    listaProds =(ArrayList<Produto>) request.getSession().getAttribute("listaProdutos");
    

    should work as expected.

    From java docs , HttpRequest#getAttribute

    java.lang.Object getAttribute(java.lang.String name) Returns the value of the named attribute as an Object, or null if no attribute of the given name exists.