【问题标题】:Can't forward to jsp when handling an exception处理异常时无法转发到jsp
【发布时间】:2021-06-05 13:04:37
【问题描述】:

所以我遇到了这个问题,我使用 tomcat 做了一个 servlet 项目,我得到了这个类,它应该处理抛出的异常,然后显示带有错误状态代码的 jsp。

public class ErrorHandler extends HttpServlet {

    private static final Logger LOGGER = Logger.getLogger(ErrorHandler.class);

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Throwable throwable = (Throwable) req.getAttribute("javax.servlet.error.exception");
        Integer statusCode = (Integer) req.getAttribute("javax.servlet.error.status_code");
        if (throwable != null) {
            LOGGER.fatal("Exception: " + throwable);
        }
        if (statusCode != null) {
            LOGGER.fatal("Error, status code: " + statusCode);
        }
        req.getRequestDispatcher("error.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

此处理程序以这种方式映射到 web.xml 中。

<servlet-mapping>
    <servlet-name>ErrorHandler</servlet-name>
    <url-pattern>/error</url-pattern>
</servlet-mapping>

<error-page>
    <exception-type>java.lang.Throwable</exception-type>
    <location>/error</location>
</error-page>

问题是,为什么我总是得到默认的 tomcat 异常页面,而不是我的。我的记录器工作得很好,所以很明显,发生异常后,方法 doGet 被调用,但是当涉及到请求调度程序时,它就不起作用了。我的 jsp 页面放在 webapp 文件夹中,靠近 WEB-INF。

【问题讨论】:

    标签: java jsp exception servlets


    【解决方案1】:

    因为error.jsp 的请求调度器只是一个调度器。 Java/tomat 不会意识到error.jsp 意味着您打算将其成为错误处理程序。它只是一个页面,就像foo.jsp。因此,该调度程序接听呼叫,可以说,注意到请求涉及错误状态,然后它又将请求转发给错误调度程序。

    【讨论】:

      猜你喜欢
      • 2014-09-14
      • 2016-11-24
      • 2014-07-25
      • 2013-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-03
      • 2017-04-05
      相关资源
      最近更新 更多