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"/>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM