作者:永恆の_☆ 地址:http://blog.csdn.net/chenghui0317/article/details/9531171
做開發的時候,有時候報錯:
java.lang.IllegalStateException: Cannot call sendError() after the response has been committed
字面上是參數異常, 在response已經提交之後 不能發送錯誤請求。
下面看個例子就一目瞭然了:
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.print("上傳成功!上傳文件爲:"+fileName+"<br/>保存的地址爲"+filePath+ "!!");
out.close();
response.sendRedirect("index.jsp");
首先,利用reponse.getWrite()獲得輸出流對象,close()之後,這裏reponse其實已經提交了。註釋下面的sendRedirect代碼,執行之後發現response已經進行已經跳轉了,只不過url沒有發生改變,並且頁面上已經有輸出上面指定的字符串。
所以當執行上面代碼之後 ,reponse 會提交兩次,服務器就不知道該怎麼辦了,所以拋出異常。
解決方案: 去掉out.close() 這裏不會因爲PrintWriter 輸出對象沒有關閉而佔用資源的。