繁体   English   中英

如何拦截Spring REST控制器中的所有请求?

[英]how to intercept all requests in spring REST controllers?

我有一堆控制器,如:

@RestController
public class AreaController {
    @RequestMapping(value = "/area", method = RequestMethod.GET)
    public @ResponseBody ResponseEntity<Area> get(@RequestParam(value = "id", required = true) Serializable id) { ... }
}

我需要拦截所有到达他们的请求,

我像这个例子一样创建了一个拦截器:

http://www.mkyong.com/spring-mvc/spring-mvc-handler-interceptors-example/

但它永远不会进入:(

因为我只使用注释,我没有XML来定义拦截器,我发现它的设置如下:

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.test.app")
public class AppConfig extends WebMvcConfigurerAdapter {

    @Bean
    public ControllerInterceptor getControllerInterceptor() {
        ControllerInterceptor c = new ControllerInterceptor();
        return c;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getControllerInterceptor());
        super.addInterceptors(registry);
    }

}

我做错了什么或者我错过了什么?

您的InterceptorControllerInterceptor不是应用程序上下文托管bean。 确保在ControllerInterceptor上放置@Component注释并将其包添加到@ComponentScan 所以,假设您的ControllerInterceptor位于com.xyz.interceptors包中,例如:

package com.xyz.interceptors;  //this is your package

@Component //put this annotation here
public class ControllerInterceptor extends HandlerInterceptorAdapter{
 // code here
}

并且您的AppConfig变为:

@ComponentScan(basePackages = { "com.test.app", "com.xyz.interceptors" })
public class AppConfig extends WebMvcConfigurerAdapter {
// ...
}

显然我做错了什么但不能说什么,

定义拦截器如:

<mvc:interceptors>
  <bean class="com.test.ControllerInterceptor" />
</mvc:interceptors> 

我很确定你也可以在纯java中定义它,但这是有效的,

答案发现于: http//viralpatel.net/blogs/spring-mvc-interceptor-example/

可能你缺少映射

registry.addInterceptor(getControllerInterceptor()).addPathPatterns("/**");

而且我知道你不必使用

super.addInterceptors(registry);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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