java.lang.IllegalStateException[轉]


  • 現象
嚴重: Servlet.service() for servlet default threw exception
java.lang.IllegalStateException
    at org.apache.catalina.connector.ResponseFacade.sendError(ResponseFacade.java:407)
    at org.apache.struts2.dispatcher.Dispatcher.sendError(Dispatcher.java:725)
    at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:483)
    at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
    at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:76)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at filters.TomcatFormFilter_UTF8.doFilter(TomcatFormFilter_UTF8.java:79)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:859)
    at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:574)
    at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1527)
    at java.lang.Thread.run(Unknown Source)



  • 緣由:

JSP文件或struts action(純servlet應用中沒發現此問題)中採用了,以下代碼:
html

    public void print2Screen(HttpServletResponse resp,String encodeString,String[] htmlCommands) throws IOException{
        resp.setCharacterEncoding(encodeString);
        ServletOutputStream httpOutput= resp.getOutputStream();
        for(String temp:htmlCommands)
            httpOutput.write(temp.getBytes());
    }



  • 深層原理:

1.Servlet規範說明,不能既調用 response.getOutputStream(),又調用response.getWriter(),不管先調用哪個,在調用第二個時候應會拋出 IllegalStateException.
2.servlet代碼中有out.write(」」),這個和JSP中缺省調用的response.getOutputStream()產生衝突.
由於在jsp中,out變量是經過response.getWriter獲得的,在程序中既用了 response.getOutputStream,又用了out變量,故出現以上錯誤。

前端

  • 解決:

法一:在JSP文件中,加入下面兩句
java

<%
out.clear();
out = pageContext.pushBody();
%>

此法的缺陷:
不少開發項目並非JSP前端,如freemarker,velocity等
形成問題的"response.getOutputStream()"並未被寫在JSP裏,而是寫在servlet/action裏

法二: 在action中,不要return 回具體的result文件,而是return null
apache

 //return SUCCESS;
 return null;
tomcat

相關文章
相關標籤/搜索