getOutputStream() has already been called for this response的解决方法

来源:互联网 发布:windows系统截屏 编辑:程序博客网 时间:2024/05/21 11:02

今天在学习ajax的时候向一个jsp页面发送请求,然后这个jsp页面接收参数后进行简单的处理并返回一个字符串:代码如下
String city = request.getParameter("city");
String state = request.getParameter("state");
String res = city + "_" + state;
byte[] bytes = res.getBytes();
ServletOutputStream output = response.getOutputStream();
output.write(bytes, 0, bytes.length);
output.flush();
        //out.clear();
//out = pageContext.pushBody();

会报下列异常:
SEVERE: Servlet.service() for servlet jsp threw exception
java.lang.IllegalStateException: getOutputStream() has already been called for this response
at org.apache.catalina.connector.Response.getWriter(Response.java:607)
at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:196)
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:179)
at org.apache.jasper.runtime.JspFactoryImpl.internalReleasePageContext(JspFactoryImpl.java:116)
at org.apache.jasper.runtime.JspFactoryImpl.releasePageContext(JspFactoryImpl.java:76)
at org.apache.jsp.ajaxserver_jsp._jspService(ajaxserver_jsp.java:98)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:98)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:331)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:329)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:265)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:172)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:875)
at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528)
at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:689)
at java.lang.Thread.run(Unknown Source)

查看相应的servlet的代码,注意红色的那行:
package org.apache.jsp;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import java.util.*;
import javax.servlet.ServletOutputStream;

public final class ajaxserver_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {

private static java.util.List _jspx_dependants;

public Object getDependants() {
return _jspx_dependants;
}

public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {

JspFactory _jspxFactory = null;
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;


try {
_jspxFactory = JspFactory.getDefaultFactory();
response.setContentType("text/html;charset=ISO-8859-1");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;

out.write("/r/n");
out.write("/r/n");

String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

out.write("/r/n");
out.write("/r/n");
out.write("<!DOCTYPE HTML PUBLIC /"-//W3C//DTD HTML 4.01 Transitional//EN/">/r/n");
out.write("<html>/r/n");
out.write(" <head>/r/n");
out.write("    <base href=/"");
out.print(basePath);
out.write("/">/r/n");
out.write("    /r/n");
out.write("    <title>My JSP 'ajaxserver.jsp' starting page</title>/r/n");
out.write("    /r/n");
out.write("/t<meta http-equiv=/"pragma/" content=/"no-cache/">/r/n");
out.write("/t<meta http-equiv=/"cache-control/" content=/"no-cache/">/r/n");
out.write("/t<meta http-equiv=/"expires/" content=/"0/">    /r/n");
out.write("/t<meta http-equiv=/"keywords/" content=/"keyword1,keyword2,keyword3/">/r/n");
out.write("/t<meta http-equiv=/"description/" content=/"This is my page/">/r/n");
out.write("/t<!--/r/n");
out.write("/t<link rel=/"stylesheet/" type=/"text/css/" href=/"styles.css/">/r/n");
out.write("/t-->/r/n");
out.write("/r/n");
out.write(" </head>/r/n");
out.write(" /r/n");
out.write(" <body>/r/n");
out.write("    ");

String city = request.getParameter("city");
String state = request.getParameter("state");
System.out.println("city :" + city);
System.out.println("state :" + state);
String res = city + "_" + state;
byte[] bytes = res.getBytes();
ServletOutputStream output = response.getOutputStream();
output.write(bytes, 0, bytes.length);
output.flush();
//out.clear();
// out = pageContext.pushBody();

out.write("/r/n");
out.write(" </body>/r/n");
out.write("</html>/r/n");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
}
} finally {
if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context);
}
}
}

我们看到在JSP页面释放资源的时候,调用了ServetResponse.getWriter()方法,之后程序即抛出异常了,查看ServletAPI发现问题:

public java.io.PrintWriter getWriter()
throws java.io.IOException

Returns a PrintWriter object that can send character text to the client. The PrintWriter uses the character encoding returned by getCharacterEncoding(). If the response's character encoding has not been specified as described in getCharacterEncoding (i.e., the method just returns the default value ISO-8859-1), getWriter updates it to ISO-8859-1.

Calling flush() on the PrintWriter commits the response.

Either this method or getOutputStream() may be called to write the body, not both.

Returns:

a PrintWriter object that can return character data to the client

Throws:

UnsupportedEncodingException - if the character encoding returned by getCharacterEncoding cannot be used

java.lang.IllegalStateException - if the getOutputStream method has already been called for this response object

java.io.IOException - if an input or output exception occurred

See Also:

getOutputStream(), setCharacterEncoding(java.lang.String)

API所言,由于ServletResponse.getOutputStream()方法和该方法都有可能被调用,来输出JSP页面的内容,如果其中的一个方法被调用了,再调用另一个方法就会抛出异常。

解决方法如下:

JSP页面中的java代码中再加两行,这两行代码的作用如下:
out.clear(); //
清空缓存的内容。
out = pageContext.pushBody(); //
参考API


public BodyContent pushBody()

Return a new BodyContent object, save the current "out" JspWriter, and update the value of the "out" attribute in the page scope attribute namespace of the PageContext.

 

Returns:

the new BodyContent

·返回一个新的BodyContent(代表一个HTML页面的BODY部分内容)
·
保存JspWriter实例的对象out
·
更新PageContextout属性的内容今天在学习ajax的时候向一个jsp页面发送请求,然后这个jsp页面接收参数后进行简单的处理并返回一个字符串:代码如下
String city = request.getParameter("city");
String state = request.getParameter("state");
String res = city + "_" + state;
byte[] bytes = res.getBytes();
ServletOutputStream output = response.getOutputStream();
output.write(bytes, 0, bytes.length);
output.flush();
        //out.clear();
//out = pageContext.pushBody();

会报下列异常:
SEVERE: Servlet.service() for servlet jsp threw exception
java.lang.IllegalStateException: getOutputStream() has already been called for this response
at org.apache.catalina.connector.Response.getWriter(Response.java:607)
at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:196)
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:179)
at org.apache.jasper.runtime.JspFactoryImpl.internalReleasePageContext(JspFactoryImpl.java:116)
at org.apache.jasper.runtime.JspFactoryImpl.releasePageContext(JspFactoryImpl.java:76)
at org.apache.jsp.ajaxserver_jsp._jspService(ajaxserver_jsp.java:98)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:98)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:331)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:329)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:265)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:172)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:875)
at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528)
at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:689)
at java.lang.Thread.run(Unknown Source)

查看相应的servlet的代码,注意红色的那行:
package org.apache.jsp;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import java.util.*;
import javax.servlet.ServletOutputStream;

public final class ajaxserver_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {

private static java.util.List _jspx_dependants;

public Object getDependants() {
return _jspx_dependants;
}

public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {

JspFactory _jspxFactory = null;
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;


try {
_jspxFactory = JspFactory.getDefaultFactory();
response.setContentType("text/html;charset=ISO-8859-1");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;

out.write("/r/n");
out.write("/r/n");

String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

out.write("/r/n");
out.write("/r/n");
out.write("<!DOCTYPE HTML PUBLIC /"-//W3C//DTD HTML 4.01 Transitional//EN/">/r/n");
out.write("<html>/r/n");
out.write(" <head>/r/n");
out.write("    <base href=/"");
out.print(basePath);
out.write("/">/r/n");
out.write("    /r/n");
out.write("    <title>My JSP 'ajaxserver.jsp' starting page</title>/r/n");
out.write("    /r/n");
out.write("/t<meta http-equiv=/"pragma/" content=/"no-cache/">/r/n");
out.write("/t<meta http-equiv=/"cache-control/" content=/"no-cache/">/r/n");
out.write("/t<meta http-equiv=/"expires/" content=/"0/">    /r/n");
out.write("/t<meta http-equiv=/"keywords/" content=/"keyword1,keyword2,keyword3/">/r/n");
out.write("/t<meta http-equiv=/"description/" content=/"This is my page/">/r/n");
out.write("/t<!--/r/n");
out.write("/t<link rel=/"stylesheet/" type=/"text/css/" href=/"styles.css/">/r/n");
out.write("/t-->/r/n");
out.write("/r/n");
out.write(" </head>/r/n");
out.write(" /r/n");
out.write(" <body>/r/n");
out.write("    ");

String city = request.getParameter("city");
String state = request.getParameter("state");
System.out.println("city :" + city);
System.out.println("state :" + state);
String res = city + "_" + state;
byte[] bytes = res.getBytes();
ServletOutputStream output = response.getOutputStream();
output.write(bytes, 0, bytes.length);
output.flush();
//out.clear();
// out = pageContext.pushBody();

out.write("/r/n");
out.write(" </body>/r/n");
out.write("</html>/r/n");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
}
} finally {
if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context);
}
}
}

我们看到在JSP页面释放资源的时候,调用了ServetResponse.getWriter()方法,之后程序即抛出异常了,查看ServletAPI发现问题:

public java.io.PrintWriter getWriter()
throws java.io.IOException

Returns a PrintWriter object that can send character text to the client. The PrintWriter uses the character encoding returned by getCharacterEncoding(). If the response's character encoding has not been specified as described in getCharacterEncoding (i.e., the method just returns the default value ISO-8859-1), getWriter updates it to ISO-8859-1.

Calling flush() on the PrintWriter commits the response.

Either this method or getOutputStream() may be called to write the body, not both.

Returns:

a PrintWriter object that can return character data to the client

Throws:

UnsupportedEncodingException - if the character encoding returned by getCharacterEncoding cannot be used

java.lang.IllegalStateException - if the getOutputStream method has already been called for this response object

java.io.IOException - if an input or output exception occurred

See Also:

getOutputStream(), setCharacterEncoding(java.lang.String)

API所言,由于ServletResponse.getOutputStream()方法和该方法都有可能被调用,来输出JSP页面的内容,如果其中的一个方法被调用了,再调用另一个方法就会抛出异常。

解决方法如下:

JSP页面中的java代码中再加两行,这两行代码的作用如下:
out.clear(); //清空缓存的内容。
out = pageContext.pushBody(); //参考API


public BodyContent pushBody()

Return a new BodyContent object, save the current "out" JspWriter, and update the value of the "out" attribute in the page scope attribute namespace of the PageContext.

 

Returns:

the new BodyContent

·返回一个新的BodyContent(代表一个HTML页面的BODY部分内容)
·保存JspWriter实例的对象out
·更新PageContextout属性的内容

 

原创粉丝点击