[Solved] java.lang.IllegalStateException: getOutputStream() has already been called for this response

1. Problem Description:

After exporting the data of a certain period of time in the database, you can get excel. Although the page can be exported smoothly, the background error is as follows: (although it does not affect the export effect, it is still uncomfortable to see the abnormality in the background.)

Warning: Servlet.service() for servlet [jsp] in context with path [/exportExcel] threw exception [java.lang.IllegalStateException: getOutputStream() has already been called for this response] with root cause
java.lang.IllegalStateException: getOutputStream() has already been called for this response
    at org.apache.catalina.connector.Response.getWriter(Response.java:678)
    at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:213)
    at org.apache.jasper.runtime.JspWriterImpl.initOut(JspWriterImpl.java:125)
    at org.apache.jasper.runtime.JspWriterImpl.flushBuffer(JspWriterImpl.java:118)
    at org.apache.jasper.runtime.PageContextImpl.release(PageContextImpl.java:194)
    at org.apache.jasper.runtime.JspFactoryImpl.internalReleasePageContext(JspFactoryImpl.java:126)
    at org.apache.jasper.runtime.JspFactoryImpl.releasePageContext(JspFactoryImpl.java:80)
    at org.apache.jsp.export_jsp._jspService(export_jsp.java:566)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:439)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

Semantically, getoutputstream() has called this response, which is the exception caused by repeated calls

2. Problem analysis:

Under tomcat, the error is usually caused by using the output stream (such as output image captcha, file download, etc.)

causes such an exception: there is out.write (“” “) in the servlet code generated by the web container, which conflicts with response.getOutputStream () invoked in JSP. That is, the servlet specification states that you cannot call both response. Getoutputstream () and response. Getwriter (). No matter which one is called first, you should throw an IllegalStateException when calling the second one, because in JSP, the out variable is actually obtained through response. Getwriter. Your program uses both response. Getoutputstream and out variable, Therefore, the above error occurred

3. Solution:

Before calling response. Getoutputstream(), clear the contents of the cache, return a new bodycontext, and update the contents of the out property of pagecontext

...
<body>
<%
    String startDate = request.getParameter("startDate");
    String endDate = request.getParameter("endDate");
    System.out.println("start time:"+startDate+"  &&&  stop time"+endDate);
    if(startDate== null || startDate.equals("")){
        startDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        System.out.println("start time:"+startDate);
    }
    if(endDate== null || endDate.equals("")){
        endDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        System.out.println(endDate);
    }else{
        endDate = endDate+" 23:59:59";
        System.out.println("stop time:"+endDate);
    }
    String fileName = new Date().getTime()+".xls";
    response.reset();
    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-disposition", "inline;filename="+fileName);
    out.clear();      //Clear the contents of the cache
    out=pageContext.pushBody(); //update the contents of the out property of the PageContext
    writeExcel(response.getOutputStream(),startDate,endDate);
%>
</body>
</html>
<%!    // equivalent to the global declaration, is used in the declaration of some variables and methods in the jsp page; the above without the exclamation mark is just an ordinary statement jsp code block
    public static void writeExcel(OutputStream os,String startDate,String endDate){
        try{
            WritableWorkbook wwb = Workbook.createWorkbook(os);
            WritableSheet sheet = wwb.createSheet("export form", 0); // the first sheet
            // Set the font
            WritableFont redfont = new WritableFont(WritableFont.createFont("Microsoft elegant black"),10, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.RED);
            // ************** adds data to the worksheet*****************
            WritableCellFormat red_key = new WritableCellFormat(redfont);
            WritableFont black_font = new WritableFont(WritableFont.createFont("Microsoft YAHEI"),10, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE,Colour.BLACK);
            WritableCellFormat black_key = new WritableCellFormat(black_font);
            // **************Adding a table header to a worksheet*****************
...
...

4

The above code doesn’t use out at all. Why can I call out. Clear and pagecontext?Because these are JSP built-in objects, can be used at any time

Nine built-in objects of JSP (can be used directly on JSP page, but not on HTML page)

4.1 page: a JSP is a servlet class, a Java class. This object of the Java class corresponds to the page object of the JSP

4.2 pagecontext: current page object

4.3 application: context object

4.4 config: servlet life cycle 1. Initialization

4.5 request: request. Servlet life cycle 2. Service method: request, response

4.6 response

4.7 session: the request corresponds to a session. With a request, you can get a session, session = request. Getsession()

4.8 out: response corresponds to out object — “this is the root of this exception

4.9 exception: exception object (if there is code, there will be exception)

Similar Posts: