如何重定向到servlet中的错误页面? [英] How to redirect to error page in servlet?

查看:87
本文介绍了如何重定向到servlet中的错误页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在web.xml中

我正在编写servlet,以防异常情况我正在重定向到我自定义的错误页面, p>

In web.xml

<error-page>
  <exception-type>java.lang.Exception</exception-type>
  <location>/WEB-INF/jsp/ErrorPage.jsp</location>
</error-page>

在Servlet中,

protected void doPost(HttpServletRequest request,
    HttpServletResponse response) throws ServletException, IOException {
try{
       //Here is all code stuff
       Throw new Exception();
}catch(Exception e){

         e1.printStackTrace();

}

但这里 ErrorPage.jsp 没有显示,我会出错的地方可以解释我吗?

But here ErrorPage.jsp is not displaying , where I am going wrong can anyone explain me?

推荐答案

问题是你捕获异常,因此没有异常将离开您的 doPost()方法。如果 Exception 匹配< exception-type> (相同或子类),则只会重定向错误页面留下你的 doPost()方法。

The problem is that you catch the Exception and therefore no Exception will leave your doPost() method. You will only be redirected error page if an Exception matching the <exception-type> (either identical or a subclass of it) leaves your doPost() method.

你应该重新抛出异常捆绑在一个 RuntimeException 中,例如:

You should rethrow the Exception bundled in a RuntimeException for example:

} catch(Exception e) {
    e1.printStackTrace();
    throw new RuntimeException(e);
}

不幸的是,如果我们在谈论一般的异常你不能只抓不到它,因为 doPost()被声明为仅抛出$ code的实例ServletException 或 IOException 。您被允许不能捕捉到这些,但 java.lang.Exception 必须被捕获。

Unfortunately if we're talking about a general Exception you can't just not catch it because doPost() is declared to only throw instances of ServletException or IOException. You are allowed not to catch those, but java.lang.Exception must be caught.

这篇关于如何重定向到servlet中的错误页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆