前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Cannot create a session after the response has been committed

Cannot create a session after the response has been committed

作者头像
猿天地
发布2018-04-03 12:20:58
3.1K0
发布2018-04-03 12:20:58
举报
文章被收录于专栏:猿天地猿天地

来源:猿天地

链接:http://cxytiandi.com/blog/detail/1699

刚好今天博客功能正式上线,然而上线之后出了一个bug

java.lang.IllegalStateException: Cannot create a session after the response has been committed

意思是说在response提交之后不能操作session了,我也就奇怪了,本地开发的时候没出现这个问题啊。

唯一不一样的是线上用的nginx做转发,还有就是我是从一个action里重定向到另外一个action时出的错。

根据异常提示看了下问题出在一个Filter里面

代码语言:javascript
复制
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
String path = req.getContextPath();
String basePath = "";
if (System.getProperty("os.name").toLowerCase().startsWith("linux")) {
    basePath = "http://cxytiandi.com";
} else {
    basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
}
if(contains(req.getRequestURI())){
    if(req.getSession().getAttribute("login_userId") == null){
resp.sendRedirect(basePath + path + "/login?backUrl=" + basePath + req.getRequestURI());
    }
} 
chain.doFilter(request, response);

这是Filter里面的代码,按照异常信息应该是下面这句代码不能在response之后操作session

req.getSession().getAttribute("login_userId")

改完后代码如下

代码语言:javascript
复制
HttpServletRequest req = (HttpServletRequest) request;
Object login_userId = req.getSession().getAttribute("login_userId");
HttpServletResponse resp = (HttpServletResponse) response;
String path = req.getContextPath();
String basePath = "";
if (System.getProperty("os.name").toLowerCase().startsWith("linux")) {
    basePath = "http://cxytiandi.com";
} else {
    basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
}
if(contains(req.getRequestURI())){
    if(login_userId == null){
resp.sendRedirect(basePath + path + "/login?backUrl=" + basePath + req.getRequestURI());
    }
} 
chain.doFilter(request, response);

在转换response之前操作session就可以了。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2016-08-30,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 猿天地 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档