简体   繁体   中英

Retrieving a ArrayList from Session variables

I am trying to retrieve information from an ArrayList that I set in the session variables. But it isn't being set correctly some where because I get a null pointer when I run searchList.isEmpty()
The servlet part:

case "searchProducts":
    ArrayList<Product> searchList = new ArrayList<>();//create array
    Product testProduct = new Product(1500,"test","testing",100); //create product
    searchList.add(testProduct); //add product to ArrayList
    session.setAttribute("searchList", searchList);//sets session value to ArrayList
    view = request.getRequestDispatcher("SearchProduct.jsp"); //set view to JSP
    break;

The JSP where I'm trying to get the info looks like this, I'm including the different things I've tried. The JSP:

<%
                ProductService ps = new ProductService();
                ArrayList<Product> searchList = (ArrayList<Product>)session.getAttribute("searchProduct");
                out.println(searchList.isEmpty());
                    //end test items


//                    if(searchList.isEmpty()== false){
//                        for(int count = 0; count < searchList.size(); count++){
//                            out.println("<option>");
//                            out.println(searchList.get(count).getName());
//                            out.println("</option>");
//                        }//end for
//                    }//end if
%>

Any help is greatly appreciated!

Typo in your code. You used "searchList" as key when you set the attribute but when you try to retreive it , you use session.getAttribute("searchProduct"); searchProduct isn't set/doesn't exist and so,

session.getAttribute("searchProduct");

returns null and gives a nullpointerexception upon calling isEmpty().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM