栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

当servlet发生异常时,如何重定向到错误页面?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

当servlet发生异常时,如何重定向到错误页面?

以通用方式处理它的唯一方法是使用

web.xml
如下所示:

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

抛出servlet

ServletException
IOException
但是如果您想在单个异常处理程序中处理运行时异常和所有其他异常,则可以将异常类型提供为
Throwable
。您可以使用多个错误页面条目,这些条目将处理不同类型的异常并具有不同的处理程序。

例:

@WebServlet("/ErrorHandler")public class ErrorHandler extends HttpServlet {    private static final long serialVersionUID = 1L;    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        processError(request, response);    }    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        processError(request, response);    }    private void processError(HttpServletRequest request, HttpServletResponse response) throws IOException {        //customize error message        Throwable throwable = (Throwable) request     .getAttribute("javax.servlet.error.exception");        Integer statusCode = (Integer) request     .getAttribute("javax.servlet.error.status_pre");        String servletName = (String) request     .getAttribute("javax.servlet.error.servlet_name");        if (servletName == null) { servletName = "Unknown";        }        String requestUri = (String) request     .getAttribute("javax.servlet.error.request_uri");        if (requestUri == null) { requestUri = "Unknown";        } request.setAttribute("error", "Servlet " + servletName +" has thrown an exception " + throwable.getClass().getName() +          " : " + throwable.getMessage()); request.getRequestDispatcher("/ErrorPage.jsp").forward(request, response);    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/447320.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号