日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

問題記錄:HttpServletRequestWrapper導致跨域失敗的問題

作者:何憶清風 更新時間: 2022-06-08 編程語言

記錄一次自己搭建項目時,使用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

欄目分類
最近更新