protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name"); // get param
List<String> list = new ArrayList<String>(); // create list
HttpSession session = request.getSession(); // create a session handler object
// if this is new session , add the param to the list, then set the list as session atr
if(session.isNew()) {
System.out.println("in new session");
// this is a new session , add the param to the new list, then add list to session atr
list.add(name);
session.setAttribute("list", list);
}else{
System.out.println("in old session");
// THIS SESSION ALREADY EXISTS (THERE IS DATA IN LIST THAT WE NEED, THAT DATA IS STORED IN SESSION ATR)
// get the session atr , then store the content of a atr list, to this new list
list = (List<String>)session.getAttribute("list");
// add the new item to the list
list.add(name);
// set the new session atr, now with this newly added item
session.setAttribute("list", list);
}
Run Code Online (Sandbox Code Playgroud)
我的评论几乎就是这么说的.我从jsp页面重定向来自提交的地方,获取名称,创建列表和会话处理程序.
该程序的一点是将用户输入保存在列表中.显然,我需要会话,所以我可以在用户之间做出改变,并为不同的用户提供不同的列表.我在else语句中获取空指针异常,我尝试检索已存在的列表,以便我可以在其中添加更多项.我错过了什么?谢谢
这确实不是维护会话范围对象的正确方法.您依赖于HttpSession#isNew()哪个只会true在HTTP会话是新会话时返回,而不是在会话范围对象不存在时返回.如果在调用servlet之前已经(隐式)创建了会话,那么isNew()将返回false.例如,当您<%@page session="false" %>在同一会话中未事先打开JSP页面时.
您应该检查是否存在感兴趣的会话作用域对象.
所以,而不是:
HttpSession session = request.getSession();
List<String> list = new ArrayList<String>();
if (session.isNew()) {
list.add(name);
session.setAttribute("list", list);
} else {
list = (List<String>) session.getAttribute("list");
list.add(name);
session.setAttribute("list", list);
}
Run Code Online (Sandbox Code Playgroud)
你应该这样做:
HttpSession session = request.getSession();
List<String> list = (List<String>) session.getAttribute("list");
if (list == null) {
list = new ArrayList<String>();
session.setAttribute("list", list);
}
list.add(name);
Run Code Online (Sandbox Code Playgroud)
请注意,您不需要将该列表放回会话中.会话不会保留List对象的副本,因为您在PHP等过程语言中的期望.Java是一种面向对象的语言.会议认为该副本参考的List对象.对可变对象的所有更改都会List反映在所有引用中.
要了解HTTP会话的工作原理,请访问servlet如何工作?实例化,会话,共享变量和多线程.
| 归档时间: |
|
| 查看次数: |
8034 次 |
| 最近记录: |