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