做毕设的时候,文件能够正常下载但是后台报错,于是查阅了下,发现以下的解决方法。
现象:
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应用中没发现此问题)中采用了,如下代码:
public void print2Screen(HttpServletResponse resp,String encodeString,String[] htmlCommands) throws IOException{ |
深层原理
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
//return SUCCESS; |
很好的解决了问题,同时也明白了相应的原理。