servlet /过滤器在java中的特定异常处理 [英] Servlet/filter specific exception handling in java

查看:1125
本文介绍了servlet /过滤器在java中的特定异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个servlet扩展为 HttpServlet 并实现一个 GET 请求。我也使用映射到上面的servlet url的过滤器(来自外部库)。现在,过滤器抛出异常,并且按预期,我得到这个

I have a servlet extending HttpServlet and implementing a GET request. I also use a filter (from an external library) which is mapped to the above servlet url. Now an exception is thrown by the filter, and as expected I get this


SEVERE:Servlet.service()for servlet [myServlet] in上下文与
路径[]抛出异常

SEVERE: Servlet.service() for servlet [myServlet] in context with path [] threw exception

我知道错误页描述可能是捕获此异常的标准方法,但是有没有办法从特定的servlet过滤器捕获异常?我已经有一个错误页面描述并重定向到一个简单的html页面。我也不想重定向到jsp页面等等,并且玩弄错误参数。简而言之,我的问题是:

I know error-page description is probably a standard way to catch this exception, but is there a way to catch the exception from a specific servlet filter ? I already have an error-page description and redirecting to a simple html page. I also don't want to redirect to a jsp page or so, and play around with error parameters. In short, my questions are :


  • 有一个更简单,优雅的方式来捕获特定 的异常servlet并处理它们? 错误页面描述符似乎没有任何字段来选择引发异常的servlet。

  • 是否可以由于过滤器引发的异常不是自定义异常,因此捕获特定过滤器中的异常并处理它们。

  • Is there a simpler, elegant way to catch an exception for a specific servlet and handle them ? The error-page descriptor doesn't seem to have any fields to choose the servlet which throws an exception.
  • Is it possible to catch an exception occuring inside a specific filter and handle them, given that the exception thrown by the filter is not a custom exception ?

推荐答案

你不能扩展Filter并处理超级抛出的异常?

Can you not extend the Filter and handle the exception thrown by 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);
                    }
              }
       }
}

这篇关于servlet /过滤器在java中的特定异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆