来源:猿天地
链接: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里面
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")
改完后代码如下
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就可以了。