gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 19:54:49 24 4
gpt4 key购买 nike

我正在编写一个 servlet,如果发生任何异常,我不想在浏览器上显示异常/错误消息,所以我将重定向到我的自定义错误页面。所以我这样做了:

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

request.getRequestDispatcher("/ErrorPage.jsp").forward(request, response);
e1.printStackTrace();

}

这是正确的方法吗,如果我错了请指正,如果有更好的机制请告诉我。

最佳答案

以通用方式处理它的唯一方法是使用 web.xml,如下所示:

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

servlet 被抛出 ServletExceptionIOException 但如果你想在一个异常处理程序中处理运行时异常和所有其他异常,你可以提供异常类型 可抛出。您可以使用多个错误页面条目来处理不同类型的异常并具有不同的处理程序。

示例:

@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_code");
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);
}
}

关于java - servlet 发生异常时如何重定向到错误页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26801038/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com