如何在spring mvc中对特定请求执行过滤器?

时间:2017-10-26 12:16:21

标签: java spring spring-mvc java-ee spring-boot

以下是过滤器。

subscribedGroups

以下是资源 我想仅针对第二个请求执行上面的过滤器。

如何做到,请帮助......

@Component
public class TestFilter extends GenericFilterBean {

@Override
public void doFilter(
  ServletRequest request, 
  ServletResponse response,
  FilterChain chain) throws IOException, ServletException {
    chain.doFilter(request, response);
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    System.out.println("token is: "+httpRequest.getHeader("token"));
}    
}

1 个答案:

答案 0 :(得分:1)

您可以尝试使用HandlerInterceptorAdapter。它的工作原理是url,而不是特定的方法,所以它不是你想要的,但它应该有效:

public class MyInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //To work with a specific method on the url
        if(request.getMethod().equals("GET")){
            //Do stuff
        }

        return super.preHandle(request, response, handler);
    } 

    //There is also a postHandle and postCompletion method that can be override     
}

并在WebMvcConfigurerAdapter注册:

public class SpringMvcContextConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/yourUrl");
    }
}

另一个解决方案是使用带有spring-mvc的Aspect并在方法上设置PointCut。

希望它有所帮助。