简体   繁体   中英

JSP - ArrayList in session attribute null

I am trying to store some data in a arraylist in each users session however when I try and grab the list it is apparently null...

Code:

<%
    List<String> attacks = new ArrayList<>();
    if (request.getSession().getAttribute("attackList") != null){
        attacks = (List<String>) request.getAttribute("attackList");
        int x = 1;
        for (String attack : attacks){
            String[] attacc = attack.split(":");
            out.print("" +
                    "<tr>\n" +
                    "                                    <th scope=\"row\">"+x+"</th>\n" +
                    "                                    <td>"+attacc[0]+"</td>\n" +
                    "                                    <td>"+attacc[1]+"</td>\n" +
                    "                                    <td>"+attacc[2]+"</td>\n" +
                    "                                    <td>"+attacc[3]+"</td>\n" +
                    "                                </tr>");
            x++;
        }
    }else{
        out.print("empty");
    }
%>

That ^ is the code I am using to fetch the data, it is printing "empty", so its essentially null... How I am adding the data:

if (request.getAttribute("attackList") != null) {
    attacks = (List<String>) request.getAttribute("attackList");
    request.removeAttribute("attackList");
}
attacks.add("data here");
request.setAttribute("attackList", attacks);

I have not tried anything due to me not knowing what to try here.

First, I suggest you, if it is possible, you can start working with expression language, instead of jsp directly, because turn your code more readable. Look your problem, do you want to work with a List in a Request our a Session scope? I ask because sometimes you get your list from request scope but your IF is verifying the Session.

And at no time are you adding your list to the session. You could do this, after your logic, with:

request.getSession().setAttribute("attackList", attacks);

Here is more about session methods:

https://beginnersbook.com/2013/11/jsp-implicit-object-session-with-examples/

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