关于 Cannot forward after response has been committed的错误

这个错误顾名思义:就是在给客户端做出提交响应完毕后,就不能再次使用request的转发。

代码原先是这样的:

 1 package com.bdqn.jsp.study.web.filter;
 2 
 3 import javax.servlet.*;
 4 import javax.servlet.annotation.WebFilter;
 5 import javax.servlet.http.HttpServletRequest;
 6 import javax.servlet.http.HttpServletResponse;
 7 import java.io.IOException;
 8 
 9 @WebFilter(filterName = "checkLoginFilter", urlPatterns = "/*")
10 public class CheckLoginFilter implements Filter {
11     @Override
12     public void init(FilterConfig filterConfig) throws ServletException {
13 
14     }
15 
16     @Override
17     public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
18         HttpServletRequest request = (HttpServletRequest) servletRequest;
19         HttpServletResponse response = (HttpServletResponse) servletResponse;
20         if (request.getRequestURI().contains("/user")) {
21             Object value = request.getSession().getAttribute("user");
22             if (value == null) {
23                 response.sendRedirect(request.getContextPath() + "/login.jsp");
24                 //return;
25             }
26         }
27         filterChain.doFilter(request, response);
28     }
29 
30     @Override
31     public void destroy() {
32 
33     }
34 }

注意这里是个filter主要作用:用于判断用户是否登录后才能访问相关页面,地址栏里有“/user”的地址信息,就认为改地址是登录后才能进行访问

然而在某一个servlet里有如下相关代码:

  if (returnValue != null) {
      request.getRequestDispatcher("/" + returnValue.toString()).forward(request, response);
  }

如果这么写就出问题了,因为在filter里response做出重定向后,还要执行doFilter方法,因此当执行servlet中的转发操作时就会报错了,因为在response.sendRedirect()会认为已经给response的commited属性设置成true了,因此不能再进行转发

上一篇:OpenCL memory object 之 Global memory (1)


下一篇:使用WebStorm进行javascript调试