我有一个扩展 HttpServlet
并实现 GET
请求的 servlet。我还使用映射到上述 servlet url 的过滤器(来自外部库)。现在过滤器抛出一个异常,正如我预期的那样
SEVERE: Servlet.service() for servlet [myServlet] in context with path [] threw exception
我知道 error-page
描述可能是捕获此异常的标准方法,但是有没有办法从特定的 servlet 过滤器捕获异常?我已经有一个 error-page
描述并重定向到一个简单的 html 页面。我也不想重定向到 jsp 页面左右,并尝试使用错误参数。简而言之,我的问题是:
- 是否有更简单、优雅的方法来捕获特定 servlet 的异常并处理它们?
error-page
描述符似乎没有任何字段来选择引发异常的 servlet。 - 如果过滤器抛出的异常不是自定义异常,是否有可能捕获并处理发生在特定过滤器内的异常?
最佳答案
能不能不扩展Filter,处理super抛出的异常?
public class MyFilter extends CustomFilter{
private static final Map<String, String> exceptionMap = new HashMap<>();
public void init(FilterConfig config) throws ServletException {
super.init(config);
exceptionMap.put("/requestURL", "/redirectURL");
exceptionMap.put("/someOtherrequestURL", "/someOtherredirectURL");
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
try{
super.doFilter(request, response, chain);
}catch(Exception e)
//log
String errURL = exceptionMap.get(request.getRequestURI());
if(errURL != null){
response.sendRedirect(errURL);
}
}
}
}
关于java - Java 中的 Servlet/过滤器特定异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29914717/