網站首頁 編程語言 正文
記錄一次自己搭建項目時,使用Filter實現統一響應體時遇到的跨域問題。
問題:定義了兩個Filter過濾器,設置 corsFilter優先執行,ResponseFilter在執行后將返回體重新設置。導致跨域失敗
@Configuration
public class ApplicationAutoConfig {
@Bean
public FilterRegistrationBean<CorsFilter> corsFilter() {
//1. 添加 CORS配置信息
CorsConfiguration config = new CorsConfiguration();
//放行哪些原始域
config.addAllowedOrigin("http://localhost:8080");
//是否發送 Cookie
config.setAllowCredentials(true);
//放行哪些請求方式
config.addAllowedMethod("*");
//放行哪些原始請求頭部信息
config.addAllowedHeader("*");
//暴露哪些頭部信息
config.addExposedHeader("*");
//2. 添加映射路徑
UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
corsConfigurationSource.registerCorsConfiguration("/**", config);
//3. 返回新的CorsFilter
FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean(new CorsFilter(corsConfigurationSource));
bean.setOrder(0);
bean.addUrlPatterns("/*");
return bean;
}
@Bean
public FilterRegistrationBean<ResponseFilter> responseFilter() {
FilterRegistrationBean<ResponseFilter> bean = new FilterRegistrationBean(new ResponseFilter());
bean.setOrder(Integer.MAX_VALUE);
return bean;
}
}
由于在ReponseFilter中將request和reponse請求進行了封裝,wrapResponse()方法中,將緩存中數據取出來后,會執行重置緩存區,原來調用的是 reset() 方法,reset方法會調用父類的reset方法去把reponse中的數據也清除掉包括設置的跨域頭信息等,所以我們只需要清除掉緩存區中;將 reset()方法換成 resetBuffer() 即可
@Override
public void reset() {
super.reset();
this.content.reset();
}
//調用的super方法
public void reset() {
this.response.reset();
}
public class ResponseFilter extends OncePerRequestFilter {
//過濾掉swagger路徑
private static final Set<String> ALLOWED_PATH = Collections.unmodifiableSet(
new HashSet<>(Arrays.asList(
"/swagger-ui.html",
"/v2/api-doc",
"/swagger-resources",
"/webjars")));
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(request);
ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response);
filterChain.doFilter(requestWrapper, responseWrapper);
wrapResponse(responseWrapper);
responseWrapper.copyBodyToResponse();
}
/**
* 復寫返回值信息
*
* @param response
* @throws IOException
*/
private void wrapResponse(ContentCachingResponseWrapper response) throws IOException {
byte[] b = response.getContentAsByteArray();
// 重置response中的body中的數據,不能使用reset()方法
if (b.length > 0) {
response.resetBuffer();
}
// 通過response的outputStream寫入新的數據
ServletOutputStream outputStream = response.getOutputStream();
outputStream.write(JSON.toJSONBytes(ResponseData.ok(JSON.parse(b))));
}
/**
* 跳過swagger路徑
*
* @param request
* @return
*/
@Override
protected boolean shouldNotFilter(HttpServletRequest request) {
//過濾掉swagger路徑
String path = request.getRequestURI().substring(request.getContextPath().length()).replaceAll("[/]+$", "");
return ALLOWED_PATH.stream().anyMatch(path::startsWith) || StringUtils.isBlank(path);
}
}
原文鏈接:https://blog.csdn.net/weixin_43915643/article/details/122420505
相關推薦
- 2022-11-09 grep正則表達式匹配中括號的方法實例_正則表達式
- 2022-07-01 c++超細致講解引用_C 語言
- 2023-03-26 C#?cefSharep控件的使用詳情_C#教程
- 2023-03-04 linux服務器CPU飆高排查分析_Linux
- 2022-10-14 element tree懶加載默認展開指定節點
- 2022-11-20 WPF實現自帶觸控鍵盤的文本框_C#教程
- 2022-08-01 MongoDB基礎之集合操作_MongoDB
- 2023-02-04 Rust?語言的全鏈路追蹤庫?tracing使用方法_Rust語言
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支