【问题标题】:Why is sendRedirect(String path) not throwing IllegalStateException?为什么 sendRedirect(String path) 不抛出 IllegalStateException?
【发布时间】:2013-12-19 03:10:50
【问题描述】:

我的 servlet 中有以下代码

  public class RedirectingExceptionServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        out.println("Hello, response is being committed");
        out.flush();
        response.sendRedirect("redirectedExceptionServlet");
        System.out.println("Tried redirecting after committing response");
    }

}

这里,我尝试在响应提交后重定向。

根据规范Send Redirect java doc sendRedirect(String) 如果您在响应提交后尝试调用 sendRedirect(path) 应该抛出 IllegalStateException

我看到一个带有消息的页面:您好,正在提交响应

另一个有趣的事情是,我无法在服务器控制台中看到“提交响应后尝试重定向”的语句

有人可以解释一下这种行为吗?

环境详情:Windows 7、Tomcat 7.0.47、J2EE-6

【问题讨论】:

  • 我通过尝试很少的东西学到的是,一旦容器遇到 out.flush();它从那里返回并且不执行剩余的代码行或简单地忽略它们。如果我的理解有误,请指正。

标签: redirect tomcat7 java-ee-6 servlet-3.0


【解决方案1】:

一旦容器遇到 out.flush();它从那里返回并且不执行剩余的代码行或简单地忽略它们,这仅在 out.flush() 之前没有重定向的情况下才是正确的;

我尝试了很多组合。如果有人有兴趣看看这些组合,我可以分享它们

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-23
    • 2021-07-19
    • 1970-01-01
    • 2011-07-07
    • 2012-04-23
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    相关资源
    最近更新 更多