java - 向支持 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 {
我当然可以从参数中读取参数、标头值等,但我想知道是否已经支持其他方式。
过滤器出现在某种文档中(我正在使用Swagger和SpringFox)将是一个加号。
主配置类
@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));
}
}
解决方案
推荐阅读
- node.js - 将多个 .ts 文件打包成单个 bundle.js 文件
- cmake - 似乎无法在我的 cmake 项目 Ubuntu 中包含 Glut
- docker-compose - “jupyter labextension enable”找不到扩展
- mysql - 在 id 上重复键更新。传递id的正确方法
- python - 如何在 for 循环中排除列表的某些数字
- docker - 同一个 docker compose 服务在多个文件夹中
- java - Firebase中数据更改的数据检索出现错误
- javascript - 如何在 TypeOrm 中模拟 EntityManager.transaction() 的测试?
- c++ - 如何使用 libclang 获得函数的深度?
- android - 如何在 Android Studio 中拥有不同的代码风格