问题描述
如何正确处理servlet中遇到的错误?现在,我继承的应用程序(仅使用普通的JSP / Servlet)有一个名为 Controller
的超类,它扩展了 HttpServlet
以及所有其他servlet的扩展。在那个控制器
类是一个try和catch块,如下所示:
How do you properly handle errors encountered in a servlet? Right now, the app that I inherited (uses only plain JSP/Servlet) has a superclass called Controller
which extends HttpServlet
and which all other servlets extend from. In that Controller
class is a try and catch block like the following:
try {
// execute doPost or doGet here
} catch (Exception e) {
// show a generic error page
}
这是正确的做法吗?它似乎很笨重,似乎并不总是奏效。我只是一名实习生,所以我没有很多经验。任何建议?我正在努力让应用程序变得健壮..
Is this the proper way of doing it? It seems clunky and doesn't seem to always work. I'm only an intern so I don't have a lot of experience with this. Any advice? I'm trying to make the app for robust..
推荐答案
要做的标准是让你的Servlet doXxx()
方法(例如 doGet()
, doPost()
,抛出 ServletException
并允许容器捕获并处理它。您可以使用< error-page> WEB-INF / web.xml
中显示的自定义错误页面c>标签:
The standard thing to do is have your Servlet's doXxx()
method (eg. doGet()
, doPost()
, etc.) throw a ServletException
and allow the container to catch and handle it. You can specify a custom error page to be shown in WEB-INF/web.xml
using the <error-page>
tag:
<error-page>
<error-code>500</error-code>
<location>/error.jsp</location>
</error-page>
如果您最终捕获异常
您无法优雅地处理,只需将其包装在 ServletException
中,如下所示:
If you end up catching an Exception
you can't elegantly handle, just wrap it in a ServletException
like this:
try {
// code that throws an Exception
} catch (Exception e) {
throw new ServletException(e);
}
这篇关于如何正确处理JSP / Servlet应用程序中的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!