Today, I wrote the java verification code program. After the program is completed, everything is normal, but java is always thrown. lang. illegalStateException is abnormal. Although it does not affect normal use, it is uncomfortable to check the code. Finally, I checked a lot of information online and finally found the cause.
When uploading, downloading, or filtering files, we may need to use the output stream of the page.
For example, in JSP:
Response. reset ();
Response. setContentType ("application/vnd. ms-excel ");
OutputStream OS = response. getOutputStream ();
Throw an exception:
ERROR [Engine] StandardWrapperValve [jsp]: Servlet. service () for servlet jsp threw exception
Java. lang. IllegalStateException: getOutputStream () has already been called for this response
I found the following information from the Internet and analyzed the cause:
This is because the servlet code generated by the web container contains out. write ("), which conflicts with response. getOutputStream () called in JSP.
That is, the Servlet specification description cannot call either response. getOutputStream () and call response. getWriter (), no matter which one is called first, the IllegalStateException should be thrown during the second call, because in jsp, The out variable is through response. getWriter uses response in the program. the above error occurs because the out variable is used again in getOutputStream.
Solution:
1. Add in the program:
Out. clear ();
Out = pageContext. pushBody ();
You can;
2. Do not include spaces or line breaks between %] [%
3. flush () is required when writing images to the page ()
OutputStream output = response. getOutputStream ();
Output. flush ();
4. Write <meta http-equiv = "Content-Type" content = "text/html; charset = gb2312">
Some people say it may be a tomcat bug. I sent a letter to her:
: I looked at this, http://www.javathinker.org/main. jsp? Bc = showessay. jsp + filename = tomcat/tomcat_question_chapter13.htm here is a post you reply to. The points in it are basically the same as I understand, but you may write a tomcat bug at last, I want to explain: in jsp, out is an embedded object, that is, PrintWriter out = response has been set. getWriter (); in this way, when getOutputStream () again gets the output stream (for example, when forwarding filtering and downloading files), an error occurs (write rejection lock ), I see more than once that someone's file download page keeps printing this exception in the background. The servlet does not have the default out Built-in object, so there is no error. you can try to add an out object in the servlet. An exception is reported. therefore, the correct processing method should be: Make a control layer in the servlet, and do not get out objects before business processing, the out object echo operation result is generated when the business operation fails or an exception occurs.
Author: "StudyBao"