Cannot forward after response has been committed问题的解决
Cannot forward after response has been committed问题的解决
Cannot forward after response has been committed问题解决及分析
通过TOMCAT把系统启动,可以正常登陆门户,登陆进去选择子系统的时候点击登陆的时候,可是去又回到了登陆界面,如此反复就是不能够进入子系统,查看后台报的错误:
Cannot forward after response has been committed
中文意思就是已经有提交了,不能够再次转向了,然后根据JSP标签中设置的错误页面又回到了登陆页面。
(核心:同一个servlet(并且该servlet里面存在重定向或者请求转发)被多次访问,而导致了上面出现的错误)。见我出现错误的例子:
package sc.tl.filter; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.websocket.Session; /** * Servlet Filter implementation class adminLogin */ @WebFilter("/manage/*") public class adminLogin implements Filter { public void destroy() { } /** * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //父类转子类 HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; //设置字符集 request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); HttpSession s = req.getSession(); //获取session中的isAdmin的值 String flag = (String)s.getAttribute("isAdminLogin"); String spath = req.getRequestURI().substring(req.getContextPath().length()); if(spath.contains("admin_")) { if(flag!=null && flag.equals("1")) { chain.doFilter(request, response); return; //出现上述问题的地方 } else { PrintWriter out = response.getWriter(); out.write("<script>"); out.write("alert('请先登录管理员用户账号!');"); out.write("location.href='login.jsp';"); out.write("</script>"); out.close(); return; } } chain.doFilter(request, response); } /** * @see Filter#init(FilterConfig) */ public void init(FilterConfig fConfig) throws ServletException { // TODO Auto-generated method stub } }
上面的代码是一个关于用户访问管理员页面的一个过滤器。如果是管理员且登录那么就转发到相应的servlet或者jsp页面中去,否则就决绝访问。
而我找了一半天的错误竟然是管理员验证成功
chain.doFilter(request, response);
之后,忘记return跳出了,导致再一次执行了最后面的
chain.doFilter(request, response);
也就是说如果是管理员可以访问的servlet和jsp,那么始终会访问两次,就会爆Cannot forward after response has been committed的错误!
自己注意查看,出现这样的错误,肯定是不注意的是后访问了两次。