欧美一区二区三区,国内熟女精品熟女A片视频小说,日本av网,小鲜肉男男GAY做受XXX网站

SpringBoot下如何配置實現跨域請求

錢淋西2年前15瀏覽0評論

SpringBoot下如何配置實現跨域請求?

一般有三種方式,第一種最快最簡單的就是使用注解,第二種是使用Filter,第三種是是配置使用CorsFilter和CorsConfiguration方法。

注解

在controller層,增加注解@CrossOrigin,這種方式要求我們每一個controller都需要定義該注解

Filter

過濾器使用response,通過設置響應體完成跨域

import javax.servlet.*; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Component public class CorsFilter implements Filter { final static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(CorsFilter.class); public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "x-requested-with"); System.out.println("*********************************過濾器被使用**************************"); chain.doFilter(req, res); } public void init(FilterConfig filterConfig) {} public void destroy() {} }Bean方法import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; @Configuration public class CorsConfig { private CorsConfiguration buildConfig() { CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedOrigin("*"); // 1允許任何域名使用 corsConfiguration.addAllowedHeader("*"); // 2允許任何頭 corsConfiguration.addAllowedMethod("*"); // 3允許任何方法(post、get等) return corsConfiguration; } @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", buildConfig()); // 4 return new CorsFilter(source); } }

希望我的回答對你有所幫助

header java,SpringBoot下如何配置實現跨域請求