【问题标题】:Handling Exception when calling forward on a RequestDispatcher在 RequestDispatcher 上调用 forward 时处理异常
【发布时间】:2014-09-01 14:51:47
【问题描述】:

这是我的代码。

try {
    RequestDispatcher d = request
            .getRequestDispatcher("messages/error.jsp");
    request.setAttribute("message", "Error Occurred !!!");
    d.forward(request, response);
} catch (ServletException se) {
    se.printStackTrace();
} catch (IOException ioe) {
    ioe.printStackTrace();
}

我需要知道如何处理给定代码中的ServletExceptionIOException。我希望将用户重定向到错误页面并告诉用户在遇到上述异常时发生错误。

我该怎么做?

【问题讨论】:

标签: jsp jakarta-ee servlets


【解决方案1】:

您可以配置您的服务器以处理特定的异常类或状态代码,在您的情况下,您必须将下一行添加到您的 web.xml

<error-page>
   <exception-type>javax.servlet.ServletException</exception-type>
   <location>/error.jsp</location>
</error-page>

IOException 一样,使用这个配置,当应用服务器捕获到一个未处理的ServletException 时会显示error.jsp。 error.jsp 页面应该有属性 isErrorPage="true",这样您就可以访问包含与抛出的异常相关的所有信息的exception 变量。我举了一个显示堆栈跟踪的示例。

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" isErrorPage="true" %>
<html>
<head>
   <title>Error Handling Example</title>
</head>
<body>
     <%=exception.getMessage()%>
     <% exception.printStackTrace(response.getWriter()); %>
</body>
</html>

您还需要删除 catch 块代码。

【讨论】:

  • 去掉处理异常的代码,去掉}catch (ServletException se) { }块,如果你的代码没有处理异常,服务器AS只带你到error.jsp,所以你应该删除 try catch 块
【解决方案2】:

您可以在您的 catch 块中遇到异常时重定向:示例:

try {
    //Do whatever you need here
} catch (ServletException se) {
request.setAttribute("message", "Error Occurred !!! + \n"+ se.getMessage());
RequestDispatcher d = request
            .getRequestDispatcher("messages/error.jsp");
    d.forward(request, response);
    se.printStackTrace();
} catch (IOException ioe) {
 request.setAttribute("message", "Error Occurred !!! + \n"+ se.getMessage());
RequestDispatcher d = request
            .getRequestDispatcher("messages/error.jsp");
    d.forward(request, response);
    ioe.printStackTrace();
}

然后在你的error.jsp中你需要获取属性;

${message}//recommended

或者如果您使用不推荐的 scriplets,请执行以下操作:

request.getAttribute("message");

【讨论】:

  • d.forward(request, response); 在 catch 块中也给出了处理异常的消息。我应该如何处理它们?
猜你喜欢
  • 1970-01-01
  • 2011-11-14
  • 2013-09-11
  • 2021-07-10
  • 2017-09-30
  • 2021-08-06
  • 1970-01-01
  • 2012-03-13
  • 2013-07-24
相关资源
最近更新 更多