简体   繁体   English

JSP - ArrayList 在 session 属性 null

[英]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...我正在尝试在每个用户 session 的 arraylist 中存储一些数据,但是当我尝试获取列表时,它显然是 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:那 ^ 是我用来获取数据的代码,它正在打印“空”,所以它本质上是 null ......我如何添加数据:

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.首先,我建议你,如果可能的话,你可以开始使用表达式语言,而不是直接使用 jsp,因为让你的代码更具可读性。 Look your problem, do you want to work with a List in a Request our a Session scope?看看你的问题,你想在请求我们的 Session scope 中使用列表吗? I ask because sometimes you get your list from request scope but your IF is verifying the Session.我问是因为有时您会从请求 scope 中获取您的列表,但您的IF正在验证 Session。

And at no time are you adding your list to the session.而且您绝不会将您的列表添加到 session 中。 You could do this, after your logic, with:按照你的逻辑,你可以这样做:

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

Here is more about session methods:以下是有关 session 方法的更多信息:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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