拦截器放行swagger2
时间: 2023-08-02 10:31:03 浏览: 83
为了在 Spring Boot 中放行 Swagger2,你需要创建一个拦截器并将其注册到拦截器链中。可以使用以下代码来创建一个拦截器:
```java
@Component
public class SwaggerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String requestUri = request.getRequestURI();
if ("/swagger-ui.html".equals(requestUri) || "/swagger-resources".equals(requestUri)) {
return true;
}
return false;
}
}
```
这个拦截器将在请求到达控制器之前执行,并检查请求的 URI 是否是 Swagger UI 的 URI。如果是,则返回 true,否则返回 false。
然后,你需要在 WebMvcConfigurer 中将拦截器添加到拦截器链中。可以使用以下代码:
```java
@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {
@Autowired
private SwaggerInterceptor swaggerInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(swaggerInterceptor).addPathPatterns("/**");
}
}
```
这个方法将 SwaggerInterceptor 添加到拦截器链中,并将其应用于所有请求路径。这样,Swagger UI 的请求将被放行,而其他请求将被拦截。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)