问题1:Cannot create a session after the response has been committed
问题2:Cannot call sendError() after the response has been committed
- 以下是报错代码
2015-5-29 10:31:44 org.apache.catalina.core.ApplicationDispatcher invoke
严重: Servlet.service() for servlet jsp threw exception
java.lang.IllegalStateException: Cannot create a session after the response has been committed
at org.apache.catalina.connector.Request.doGetSession(Request.java:2882)
at org.apache.catalina.connector.Request.getSession(Request.java:2316)
at org.apache.catalina.connector.RequestFacade.getSession(RequestFacade.java:898)
at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:229)
at org.apache.catalina.core.ApplicationHttpRequest.getSession(ApplicationHttpRequest.java:571)
at org.apache.catalina.core.ApplicationHttpRequest.getSession(ApplicationHttpRequest.java:516)
at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:238)
at org.apache.jasper.runtime.PageContextImpl._initialize(PageContextImpl.java:146)
at org.apache.jasper.runtime.PageContextImpl.initialize(PageContextImpl.java:125)
at org.apache.jasper.runtime.JspFactoryImpl.internalGetPageContext(JspFactoryImpl.java:112)
at org.apache.jasper.runtime.JspFactoryImpl.getPageContext(JspFactoryImpl.java:65)
at org.apache.jsp.index_jsp._jspService(index_jsp.java:54)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:749)
at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:605)
at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:544)
at org.apache.struts2.dispatcher.ServletDispatcherResult.doExecute(ServletDispatcherResult.java:161)
at org.apache.struts2.dispatcher.StrutsResultSupport.execute(StrutsResultSupport.java:186)
at com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:373)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:277)
at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:176)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:263)
at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:133)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:207)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:207)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:190)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:243)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:142)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:166)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:176)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:190)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:187)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52)
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:485)
at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1008
)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1852)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)
2015-5-29 10:31:44 org.apache.catalina.core.StandardWrapperValve invoke
严重: Servlet.service() for servlet [default] in context with path [/MiniBank] threw exception
java.lang.IllegalStateException: Cannot call sendError() after the response has been committed
at org.apache.catalina.connector.ResponseFacade.sendError(ResponseFacade.java:451)
at org.apache.struts2.dispatcher.Dispatcher.sendError(Dispatcher.java:771)
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:506)
at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1008)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1852)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)
首先,采用的是SSH三框架搭建的服务端,需求是在页面上输出一段文字或者HTML代码或者JSON数据等等,当然了我们这里是输出一段文字。
疑惑点
1.是不是我们在操作的时候DAO层把session关闭导致的?
在这里我把DAO层的代码贴出来:
/**
* 查询所有记录
*
* @param classez
* 实体类
* @return 数据表中所有记录,list类型
*/
@SuppressWarnings("rawtypes")
public List hqlList(Class classez) {
// 定义list
List list = null;
// 获取session
Session session = getSession();
// HQL语句
String hql = "from " + classez.getName();
// 执行
try {
list = session.createQuery(hql).list();
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
return list;
}
大家可以看到我的session是关闭了的。
session.close();
可能大家会想这是不是出现我们根本问题的所在呢?其实不是。
这里我们做个测试,把session.close();注释掉,再次运行程序。
/**
* 查询所有记录
*
* @param classez
* 实体类
* @return 数据表中所有记录,list类型
*/
@SuppressWarnings("rawtypes")
public List hqlList(Class classez) {
// 定义list
List list = null;
// 获取session
Session session = getSession();
// HQL语句
String hql = "from " + classez.getName();
// 执行
try {
list = session.createQuery(hql).list();
} catch (Exception e) {
e.printStackTrace();
} finally {
//session.close();注释掉
}
return list;
}
修改DAO层代码:
//session.close();
错误依旧存在:
2015-5-29 11:04:03 org.apache.catalina.core.ApplicationDispatcher invoke
严重: Servlet.service() for servlet jsp threw exception
java.lang.IllegalStateException: Cannot create a session after the response has been committed
//省略更多报错代码
2015-5-29 11:04:03 org.apache.catalina.core.ApplicationDispatcher invoke
严重: Servlet.service() for servlet jsp threw exception
java.lang.IllegalStateException: Cannot create a session after the response has been committed
//省略更多报错代码
由此可见,报错并不是DAO层session引起的。
2.是不是我们的配置文件导致的?
我们去网上查阅资料发现,网上有各种各样的解决办法,比如说为Struts2添加过滤器、Spring配置、web.xml配置等等。经过测试都不行,都不是根本原因。
以下贴出完整的代码从DAO层
到service层
再到action
- BaseDao
public class BaseDao extends HibernateDaoSupport {
/**
* 查询所有记录
*
* @param classez
* 实体类
* @return 数据表中所有记录,list类型
*/
@SuppressWarnings("rawtypes")
public List hqlList(Class classez) {
// 定义list
List list = null;
// 获取session
Session session = getSession();
// HQL语句
String hql = "from " + classez.getName();
// 执行
try {
list = session.createQuery(hql).list();
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
return list;
}
}
-
RoiDao
注意这里是面向接口编程的,所以可能和大家有点不一样,但是程序整个实现的过程是一样的。大家照着我的写,或者自己修改一下代码即可。
//注意这是个接口
public interface RoiDao {
/**
* 获取所有数据记录
*
* @return 所有数据记录
*/
@SuppressWarnings("rawtypes")
public List roiAll();
}
实现类:
public class RoiDaoImpl extends BaseDao implements RoiDao {
// 获取所有数据记录
@SuppressWarnings("rawtypes")
@Override
public List roiAll() {
return hqlList(Roi.class);
}
}
-
RoiService
接口:
public interface RoiService {
/**
* 获取所有数据记录
*
* @return 所有数据记录
*/
@SuppressWarnings("rawtypes")
public List roiAll();
}
实现类:
public class RoiServiceImpl implements RoiService {
private RoiDao roiDao = null;
public RoiDao getRoiDao() {
return roiDao;
}
public void setRoiDao(RoiDao roiDao) {
this.roiDao = roiDao;
}
// 获取所有数据
@SuppressWarnings("rawtypes")
@Override
public List roiAll() {
return roiDao.roiAll();
}
}
在写web层的时候,我们先写一个BaseAction,所有Action的基类。
- BaseAction
/**
* 操作Servlet API
*
* @author y1笑而过
*
*/
public class BaseAction {
// 获取HTTPrequest
public HttpServletRequest getHttpRequest() {
return ServletActionContext.getRequest();
}
// 获取request对象
public Map<String, Object> getRequest() {
// 通过ActionContext得到request
return (Map<String, Object>) ActionContext.getContext().get("request");
}
// 获取response对象
public HttpServletResponse getResponse() {
// 通过ServletActionContext得到response
HttpServletResponse response = ServletActionContext.getResponse();
// 设置响应头与字符编码
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("utf-8");
return response;
}
// 获取session对象
public Map<String, Object> getSession() {
return ActionContext.getContext().getSession();
}
// 获取Application对象
public Map<String, Object> getApplication() {
return ActionContext.getContext().getApplication();
}
// 输出
public void outMessage(Object object) {
try {
PrintWriter out = getResponse().getWriter();
out.print(object);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
- RoiAction
public class RoiAction extends BaseAction {
private Roi roi = null;
public Roi getRoi() {
return roi;
}
public void setRoi(Roi roi) {
this.roi = roi;
}
private RoiService roiService = null;
public RoiService getRoiService() {
return roiService;
}
public void setRoiService(RoiService roiService) {
this.roiService = roiService;
}
public String roiAll() {
// 获取所有数据记录
List<Roi> rois = roiService.roiAll();
outMessage("123");
// 页面跳转
if (rois != null) {
return "roiAll";
}
return "fail";
}
}
- applicationContext.xml
<!-- 省略自动生成代码 -->
<!-- 实体类 -->
<bean id="roi" class="com.scp.entity.Roi"></bean>
<!-- DAO层 -->
<bean id="baseDao" class="com.scp.dao.Impl.BaseDao">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="roiDao" class="com.scp.dao.Impl.RoiDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- Service层 -->
<bean id="roiService" class="com.scp.service.Impl.RoiServiceImpl">
<property name="roiDao" ref="roiDao"></property>
</bean>
<!-- Action层 -->
<bean id="roiAction" class="com.scp.web.RoiAction">
<property name="roi" ref="roi"></property>
<property name="roiService" ref="roiService"></property>
</bean>
- struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="default" extends="struts-default">
<!-- 利率信息表 -->
<action name="roiAction" class="roiAction">
<result name="roiAll">/index.jsp</result>
<result name="fail">/index.jsp</result>
</action>
</package>
</struts>
-
工程结构图
当然了,大家的工程名不一定和我的一样,但是呢图中黄色高亮区域内容一定要有。【后面我们会讲解此次问题的解决办法】
3.是不是out.close导致的?
刚开始在网上搜索相关问题的时候看到这样一个解决办法,经过测试,这也不是导致出错的原因。
解决办法
-
解决办法1:
首先我们要知道出现此次问题的原因是因为我们在Response输出响应后才创建Session的。
(因为那时候服务器已经将数据发送到客户端了,即:就无法发送Session ID 了)
你只需要在你的程序中将创建访问Session的语句【request.getSession()】提前至Response输出数据之前就好了。
例如改成下面的写法OK:
ServletOutputStream ut = response.getOutputStream();
// 最好这样紧挨着 response.getOutputStream()
HttpSession seesion = request.getSession();
seesion.setAttribute("xxx", rand);
// 输出数据
out.print("hello");
out.close();
这个是网上的解决办法。 - 解决办法2:
public String roiAll() {
// 获取所有数据记录
List<Roi> rois = roiService.roiAll();
outMessage("123");
// 页面跳转
if (rois != null) {
return "roiAll";
}
return "fail";
}
大家发现了没有,我们在Action里面写的时候有个Struts的映射,即返回一个字符串对应struts.xml
对应的网页。这个动作是重定向!!!问题就在这,也就是说我们在向网页输出一段文字的时候,网页同时做了重定向操作!我们的需求是向网页输出一段文字,不需要重定向操作,那么我们就可以修改action里面的代码了,如下:
public void roiTest(){
outMessage("向页面输出字符");
}
可以看到,我们将返回值改为了void
,只需要向页面写数据,不需要跳转就可以这样写。当然了,有些是需要页面跳转的,那么我们也可以手动书写页面跳转代码即可。
在地址栏中输入localhost:8080/MiniBank/roiAction!roiTest.action
重新运行一下我们的程序,发现没有报错,程序运行正常!
y1笑而过的CSDN博客
y1笑而过的博客园
y1笑而过的新浪博客
y1笑而过的安卓巴士博客
y1笑而过的51CTO技术博客