【问题标题】:How to check if filters work? - Testing filters如何检查过滤器是否有效? - 测试过滤器
【发布时间】:2020-11-19 20:28:14
【问题描述】:

我有一个过滤器:

@WebFilter(urlPatterns = "/Mvc02")
public class Filter02 implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        some code...
    }

    public void init(FilterConfig config) throws ServletException {

    }
}

还有servlet:

@WebServlet(name = "Mvc02", urlPatterns = "/Mvc02")
public class Mvc02 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        some code...
    }
}

当我进入浏览器并输入 http://localhost:8080/servletjee_war_exploded/Mvc02 时,它会为我提供 servlet。它不应该先给我过滤器吗?如何运行过滤器?

【问题讨论】:

    标签: java servlets filter


    【解决方案1】:

    如果您希望过滤器仅适用于某些 URL 模式(并且如果您使用的是 spring),那么您必须使用 FilterRegistrationBean 注册过滤器

    @Bean
    public FilterRegistrationBean<Filter02> loggingFilter(){
        FilterRegistrationBean<Filter02> registrationBean 
          = new FilterRegistrationBean<>();
            
        registrationBean.setFilter(new Filter02());
        registrationBean.addUrlPatterns("/Mvc02");
            
        return registrationBean;    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-29
      • 1970-01-01
      • 2020-01-05
      相关资源
      最近更新 更多