首页 > 代码库 > Cannot create a session after the response has been committed

Cannot create a session after the response has been committed

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

Cannot create a session after the response has been committed