简体   繁体   中英

Spring WebFilter Mapping

I'm trying to add a WebFilter in my spring application. However, I'm not using .xml files (not even a web.xml, because my application does not need it).

So, I added to my class that extends AbstractAnnotationConfigDispatcherServletInitializer :

@Override
protected Filter[] getServletFilters() {
    return new Filter[]{new RequestFilter()};
}

And, my RequestFilter.java:

@WebFilter("/test/*")
public class RequestFilter implements Filter {

@Override
public void init(FilterConfig filterConfig) throws ServletException { }

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException { }

@Override
public void destroy() { }

I'm expecting that only requests matching /test/* pattern be filtered, but a request to any resource is filtered.

How I can mapping my filter?

Thanks.

@WebFilter - is not a Spring annotation. Spring ignores it. Method getServletFilters returns an array of filters without mapping them to URLs. So they triggered on every request. If you don't want to write url-mappings in web.xml, you can use HandlerInterceptor instead of Filter . They can be mapped programmatically in the DispatcherServletInitializer :

public class SomeInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
        // ...
        return true;
    }
}

@Configuration
@ComponentScan("com.example")
@EnableWebMvc  
public class AppConfig extends WebMvcConfigurerAdapter  {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry
          .addInterceptor(new SomeInterceptor())
          .addPathPatterns("/test/*");
    }
}

public class WebAppInitializer implements WebApplicationInitializer {
    public void onStartup(ServletContext servletContext) throws ServletException {  
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();  
        ctx.register(AppConfig.class);  
        ctx.setServletContext(servletContext);    
        Dynamic dynamic = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));  
        dynamic.addMapping("/");  
        dynamic.setLoadOnStartup(1);  
   }  
}

Or you can define you own WebFilter annotation!

At first, you need utility class for matching URL patterns:

public class GlobMatcher {
    public static boolean match(String pattern, String text) {
        String rest = null;
        int pos = pattern.indexOf('*');
        if (pos != -1) {
            rest = pattern.substring(pos + 1);
            pattern = pattern.substring(0, pos);
        }

        if (pattern.length() > text.length())
            return false;

        for (int i = 0; i < pattern.length(); i++)
            if (pattern.charAt(i) != '?' 
                    && !pattern.substring(i, i + 1).equalsIgnoreCase(text.substring(i, i + 1)))
                return false;

        if (rest == null) {
            return pattern.length() == text.length();
        } else {
            for (int i = pattern.length(); i <= text.length(); i++) {
                if (match(rest, text.substring(i)))
                    return true;
            }
            return false;
        }
    }
}

Annotation itself:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface WebFilter {
    String[] urlPatterns();
}

Pass-through functionality of URL pattern matching:

@Aspect
public class WebFilterMatcher {
    @Pointcut("within(@com.example.WebFilter *)")
    public void beanAnnotatedWithWebFilter() {}

    @Pointcut("execution(boolean com.example..preHandle(..))")
    public void preHandleMethod() {}

    @Pointcut("preHandleMethod() && beanAnnotatedWithWebFilter()")
    public void preHandleMethodInsideAClassMarkedWithWebFilter() {}

    @Around("preHandleMethodInsideAClassMarkedWithWebFilter()")
    public Object beforeFilter(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        if(args.length > 0) {
            HttpServletRequest request = (HttpServletRequest) args[0];
            Class target = joinPoint.getTarget().getClass();
            if (target.isAnnotationPresent(WebFilter.class)) {
                String[] patterns = ((WebFilter) target.getAnnotation(WebFilter.class)).urlPatterns();
                for (String pattern : patterns) {
                    if (GlobMatcher.match(pattern, request.getRequestURI())) {
                        return joinPoint.proceed();
                    }
                }
            }
        }
        return true;
    }
}

Interceptor:

@WebFilter(urlPatterns = {"/test/*"})
public class SomeInterceptor extends HandlerInterceptorAdapter { 
    @Override 
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 
        // ...
        return true; 
    }
}

And a little change in context configuration:

<beans> <!-- Namespaces are omitted for brevity -->
  <aop:aspectj-autoproxy />

  <bean id="webFilterMatcher" class="com.example.WebFilterMatcher" />

  <mvc:interceptors>
    <bean class="com.example.SomeInterceptor" />
  </mvc:interceptors>
</beans>

您可以将@Component批注添加到过滤器实现中,如果使用Spring Boot,则可以将@ServletComponentScan添加到主类中。

Another option is to register the custom filter class using a FilterRegistrationBean and NOT adding the filter itself as a bean. example:

@Bean
public FilterRegistrationBean<RequestResponseLoggingFilter> loggingFilter(){
    FilterRegistrationBean<RequestResponseLoggingFilter> registrationBean 
      = new FilterRegistrationBean<>();

    registrationBean.setFilter(new RequestResponseLoggingFilter());
    registrationBean.addUrlPatterns("/users/*");            
    return registrationBean;    
}

taken from: https://www.baeldung.com/spring-boot-add-filter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM