首页 > 解决方案 > 向支持 Rest 资源注释的 Spring 添加请求过滤器?

问题描述

我的 Spring Web 应用程序是通过 Java 注释配置的(请参阅底部的配置类)。

是否可以在一个控制器前面添加一个请求过滤器(或者可能通过某种配置添加多个),以支持@RestController方法内部可用的相同(或至少一部分)注释,例如@PathVariable,@RequestParam等?

到目前为止,我在DispatcherServlet 拦截文档中找到了有关HandlerInterceptor接口的文档,并且我按照拦截器配置中的内容进行了配置

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(ctx.getBean(CustomInterceptor.class));
}

但是拦截器实现了HandlerInterceptor接口,因此该preHandle()方法具有给定的签名:

preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

我当然可以从参数中读取参数、标头值等,但我想知道是否已经支持其他方式。

过滤器出现在某种文档中(我正在使用SwaggerSpringFox)将是一个加号。


主配置类

@EnableWebMvc
@Configuration
@EnableSwagger2
@ComponentScan(basePackages= { /* ... */ })
@PropertySource("classpath:config.properties")
public class WebappConfig implements WebMvcConfigurer {

    @Autowired
    private ApplicationContext ctx;

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        // extra Jackson configuration
    }

    // see below for this method
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(ctx.getBean(CustomInterceptor.class));
    }

}

标签: javaspringspring-mvc

解决方案


推荐阅读