Web开发中常见的java.lang.IllegalStateException错误

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


  • 原因:
JSP文件或struts action( 纯servlet应用中没发现此问题)中采用了,如下代码:
    publicvoid print2Screen(HttpServletResponse resp,StringencodeString,String[] htmlCommands) throws IOException{
      resp.setCharacterEncoding(encodeString);
      ServletOutputStream httpOutput= resp.getOutputStream();
       for(Stringtemp: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文件中,加入下面两句
<%
out.clear();
out = pageContext.pushBody();
%>
此法的缺陷:
很多开发项目并不是JSP前端,如freemarker,velocity等
造成问题的"response.getOutputStream()"并未被写在JSP里,而是写在servlet/action里

法二: 在action中,不要return 回具体的result文件,而是return null
 //returnSUCCESS;
 returnnull;




你可能感兴趣的:(struts,servlet)