Spring MVC拦截器模式

问题描述 投票:2回答:2

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

  • MYAPP /事/添加/什么
  • MYAPP /事/加
  • MYAPP /事/ addWhatever
  • MYAPP /事/ somethingelse /加
  • 等等...

我必须拦截所有包含“添加”的网址。有很多东西和一些东西......

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

  • **/加/*
  • **/加*
  • ** / 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

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

java spring spring-mvc interceptor
2个回答
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-方法是PUT,或POST请求。所以我在我的全局拦截器中检查这个:

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();
    }
}

0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.