Spring MVC拦截器模式

时间:2018-01-17 17:16:08

标签: java spring spring-mvc interceptor

我有一个拦截器,它应该拦截不同模式的网址,如:

  • 的myapp /事/添加/不管
  • 的myapp /东西/添加
  • 的myapp /东西/ addWhatever
  • 的myapp /东西/ somethingelse /添加
  • 等...

我必须拦截所有包含"添加"的网址。有很多 somethings somethingelses ......

我尝试过不同的模式,但似乎都错了:

  • ** /添加/ *
  • ** /添加*
  • ** / add / **(我在最后一个**之前添加了一个空格,因此它没有将其格式化为粗体)

拦截器类似于

public class MyInterceptor implements HandlerInterceptor {
}

我在

中配置它
@Configuration
@EnableSpringDataWebSupport
@EnableWebMvc
class MvcConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(final InterceptorRegistry registry) {                       
        registry.addInterceptor(getMyInterceptor()).addPathPatterns("**/add/*", "**/add/**", "**/add*");
    }

    @Bean
    public MyInterceptor getMyInterceptor() {
        return new MyInterceptor();
    }
}

如果我尝试访问

http://localhost:8080/myapp/something/add/somethingelse

我的拦截器没有拦截它......

2 个答案:

答案 0 :(得分:1)

我有类似的问题。以下是我的建议。

首先使用全局拦截器并检查请求uri:

public class MyInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String uri = request.getRequestURI();

        if(uri.contains("/add")){
            // do your job
        }

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

就我而言,所有add - 方法都是PUTPOST个请求。所以我在全局拦截器中检查这个:

public class MyInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String method = request.getMethod();
        if("PUT".equals(method) || "POST".equals(method)){
            // do your job
        }

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

在没有addPathPatterns的情况下配置它:

@Configuration
@EnableSpringDataWebSupport
@EnableWebMvc
class MvcConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(final InterceptorRegistry registry) {
        registry.addInterceptor(getMyInterceptor());
    }

    @Bean
    public MyInterceptor getMyInterceptor() {
        return new MyInterceptor();
    }
}

答案 1 :(得分:0)

显然可以通过将bean类型更改为“Mapped Interceptor”并将其包装来修复;虽然人们似乎不知道为什么它首先是一个问题。

基于此解决方案:https://stackoverflow.com/a/35948730/857994