有时候在操作Session时,系统会抛出如下异常
java.lang.IllegalStateException: Cannot create a session after the response has been committed
之所以会出现此类问题是因为我们在Response输出响应后才创建Session的。
(因为那时候服务器已经将数据发送到客户端了,即:就无法发送Session ID 了)
解决办法:
1.创建访问Session的语句【request.getSession()】提前至Response输出数据之前就好了。
例如改成下面的写法OK:
ServletOutputStream out = response.getOutputStream();
// 最好这样紧挨着 response.getOutputStream()
HttpSession seesion = request.getSession();
seesion.setAttribute("xxx", rand);
// 输出数据
out.print("<h1>hello</h1>");
out.close();
2.如果使用了Struts2可以在struts.xml中添加一个默认的拦截器:
<interceptor-ref name="createSession"/>
<interceptor-ref name="defaultStack"/>
本文讨论了在Web开发中如何正确处理Session,避免出现Cannot create session after response has been committed的异常,提供了两种解决方案:提前创建Session或在Struts2中配置默认拦截器。
2344

被折叠的 条评论
为什么被折叠?



