有时候在操作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"/>

 

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐