網(wǎng)站首頁 編程語言 正文
記錄一次自己搭建項目時,使用Filter實現(xiàn)統(tǒng)一響應體時遇到的跨域問題。
問題:定義了兩個Filter過濾器,設(shè)置 corsFilter優(yōu)先執(zhí)行,ResponseFilter在執(zhí)行后將返回體重新設(shè)置。導致跨域失敗
@Configuration
public class ApplicationAutoConfig {
@Bean
public FilterRegistrationBean<CorsFilter> corsFilter() {
//1. 添加 CORS配置信息
CorsConfiguration config = new CorsConfiguration();
//放行哪些原始域
config.addAllowedOrigin("http://localhost:8080");
//是否發(fā)送 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()方法中,將緩存中數(shù)據(jù)取出來后,會執(zhí)行重置緩存區(qū),原來調(diào)用的是 reset() 方法,reset方法會調(diào)用父類的reset方法去把reponse中的數(shù)據(jù)也清除掉包括設(shè)置的跨域頭信息等,所以我們只需要清除掉緩存區(qū)中;將 reset()方法換成 resetBuffer() 即可
@Override
public void reset() {
super.reset();
this.content.reset();
}
//調(diào)用的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中的數(shù)據(jù),不能使用reset()方法
if (b.length > 0) {
response.resetBuffer();
}
// 通過response的outputStream寫入新的數(shù)據(jù)
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
相關(guān)推薦
- 2022-08-27 pytest多文件執(zhí)行順序控制詳解_python
- 2022-09-20 Python?Flask中Cookie和Session區(qū)別詳解_python
- 2022-09-16 Pandas缺失值刪除df.dropna()的使用_python
- 2022-08-10 WPF中圖像處理的方法介紹_C#教程
- 2023-02-09 Rust?所有權(quán)機制原理深入剖析_Rust語言
- 2023-03-13 Pandas篩選某列過濾的方法_python
- 2022-06-30 Python+SymPy實現(xiàn)秒解微積分詳解_python
- 2022-06-18 C++深入講解初始化列表的用法_C 語言
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學習環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支