【问题标题】:Cannot call sendRedirect() after the response has been committed [duplicate]提交响应后无法调用 sendRedirect() [重复]
【发布时间】:2013-12-17 09:41:45
【问题描述】:

我有一个过滤器来检查会话是否存在。如果它不存在,我使用response.sendRedirect() 将用户重定向到登录页面。

在某些页面中它可以工作,在其他页面中它不起作用。我收到此错误Cannot call sendRedirect() after the response has been committed

似乎如果我在我的 jsp 页面中删除某些代码部分,例如 <%=variable%>,它会起作用。 但是,正如我所说,即使我有像<%=variable%> 这样的代码,它也可以在其他jsp 页面中工作。 我真的不明白这是什么问题。

我在这个论坛上阅读了一些类似的帖子,但我没有找到解决方案。

这是我的过滤器

public class SessionFilter implements Filter {

    public void destroy() {}

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        try {
            HttpServletRequest request = (HttpServletRequest) req;
            HttpServletResponse response = (HttpServletResponse) res;
            String url = request.getServletPath();

            HttpSession session = request.getSession(false);

            /*caso in cui il webserver non abbia ancora creato la sessione*/
            if (null == session) {
                reindirizza = true;
            } else {
                /*caso in cui il webserver abbia creato la sessione e l'utente  sia loggato*/
                if(session.getAttribute("loggato")!=null && session.getAttribute("loggato").equals("si")) {
                    reindirizza = false;
                }
                /*caso in cui il webserver abbia creato la sessione e l'utente  non sia loggato*/
                else {
                    reindirizza = true;
                }
            }

            chain.doFilter(req, res);
            if(reindirizza) {
                response.sendRedirect("Gestione.jsp?message=Sessione scaduta o non valida. Effettuare il Login");
            }
        } catch(Exception e) {
            System.out.println(e.getMessage());
        }
    }

    public void init(FilterConfig config) throws ServletException { }
}

【问题讨论】:

  • 你应该显示一些相关的代码..
  • 你尝试调试了吗?
  • 我试过了,但我不明白在哪里设置检查点。如果我删除了一段 html 代码,比如 div,它会在我删除大量代码后起作用。但在我的 html 代码中没有任何错误。我用 w3c 验证器检查了它。这似乎是一个“随机错误”
  • 我将部分代码复制到html代码较少的页面中,没有问题。错误似乎与页面中编写的代码量有关。

标签: java jsp servlets servlet-filters


【解决方案1】:

我也曾经遇到过相同类型的问题,即在响应提交后无法调用 sendRedirect()/forward

错误有点误导,但实际发出的结果是jsp中jstl标签的一些不当使用。例如标签没有正确终止。因此,请检查您的所有标签是否形状正确

【讨论】:

    【解决方案2】:

    在这里,您需要关闭您在 jsp 中打开的所有 out.println 和 out.flush 语句。这应该可以解决您的问题。

    【讨论】:

      【解决方案3】:

      response.sendRedirect("jsppage") 之后我也遇到了同样的问题,你应该像这样返回它

      return;
      

      sendredirect 方法之后添加上述语句然后没有问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-06-04
        • 2014-08-22
        • 2012-09-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-07
        相关资源
        最近更新 更多