Servlet/filter java 中的特定异常处理
Servlet/filter specific exception handling in java
我有一个扩展 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);
}
}
}
}
我有一个扩展 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);
}
}
}
}