當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Springboot 解决跨域的四种姿势
生活随笔
收集整理的這篇文章主要介紹了
Springboot 解决跨域的四种姿势
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Springboot 解決跨域的四種姿勢
姿勢一
實現WebMvcConfigurer#addCorsMappings的方法
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration public class CorsConfig implements WebMvcConfigurer {@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**").allowedOrigins("*").allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS").allowCredentials(true).maxAge(3600).allowedHeaders("*");} }姿勢二
重新注入CorsFilter
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 CorsFilterConfig {/*** 開啟跨域訪問攔截器** @date 2021/4/29 9:50*/@Beanpublic CorsFilter corsFilter() {//創建CorsConfiguration對象后添加配置CorsConfiguration corsConfiguration = new CorsConfiguration();//設置放行哪些原始域corsConfiguration.addAllowedOrigin("*");//放行哪些原始請求頭部信息corsConfiguration.addAllowedHeader("*");//放行哪些請求方式corsConfiguration.addAllowedMethod("*");UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();//2. 添加映射路徑source.registerCorsConfiguration("/**", corsConfiguration);return new CorsFilter(source);} }姿勢三
創建一個filter解決跨域
@Slf4j @Component @WebFilter(urlPatterns = { "/*" }, filterName = "headerFilter") public class HeaderFilter implements Filter {@Overridepublic void doFilter(ServletRequest request, ServletResponse resp, FilterChain chain) throws IOException, ServletException {HttpServletResponse response = (HttpServletResponse) resp;//解決跨域訪問報錯response.setHeader("Access-Control-Allow-Origin", "*");response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");//設置過期時間response.setHeader("Access-Control-Max-Age", "3600");response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, client_id, uuid, Authorization");// 支持HTTP 1.1.response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");// 支持HTTP 1.0. response.setHeader("Expires", "0");response.setHeader("Pragma", "no-cache");// 編碼response.setCharacterEncoding("UTF-8");chain.doFilter(request, resp);}@Overridepublic void init(FilterConfig filterConfig) {log.info("跨域過濾器啟動");}@Overridepublic void destroy() {log.info("跨域過濾器銷毀");} }姿勢四
使用CrossOrigin 注解
可以使用在單個方法上也可以使用在類上
Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface CrossOrigin {/** @deprecated as of Spring 5.0, in favor of {@link CorsConfiguration#applyPermitDefaultValues} */@DeprecatedString[] DEFAULT_ORIGINS = {"*"};/** @deprecated as of Spring 5.0, in favor of {@link CorsConfiguration#applyPermitDefaultValues} */@DeprecatedString[] DEFAULT_ALLOWED_HEADERS = {"*"};/** @deprecated as of Spring 5.0, in favor of {@link CorsConfiguration#applyPermitDefaultValues} */@Deprecatedboolean DEFAULT_ALLOW_CREDENTIALS = false;/** @deprecated as of Spring 5.0, in favor of {@link CorsConfiguration#applyPermitDefaultValues} */@Deprecatedlong DEFAULT_MAX_AGE = 1800;/*** Alias for {@link #origins}.*/@AliasFor("origins")String[] value() default {};/*** A list of origins for which cross-origin requests are allowed. Please,* see {@link CorsConfiguration#setAllowedOrigins(List)} for details.* <p>By default all origins are allowed unless {@code originPatterns} is* also set in which case {@code originPatterns} is used instead.*/@AliasFor("value")String[] origins() default {};/*** Alternative to {@link #origins()} that supports origins declared via* wildcard patterns. Please, see* @link CorsConfiguration#setAllowedOriginPatterns(List)} for details.* <p>By default this is not set.* @since 5.3*/String[] originPatterns() default {};/*** The list of request headers that are permitted in actual requests,* possibly {@code "*"} to allow all headers.* <p>Allowed headers are listed in the {@code Access-Control-Allow-Headers}* response header of preflight requests.* <p>A header name is not required to be listed if it is one of:* {@code Cache-Control}, {@code Content-Language}, {@code Expires},* {@code Last-Modified}, or {@code Pragma} as per the CORS spec.* <p>By default all requested headers are allowed.*/String[] allowedHeaders() default {};/*** The List of response headers that the user-agent will allow the client* to access on an actual response, other than "simple" headers, i.e.* {@code Cache-Control}, {@code Content-Language}, {@code Content-Type},* {@code Expires}, {@code Last-Modified}, or {@code Pragma},* <p>Exposed headers are listed in the {@code Access-Control-Expose-Headers}* response header of actual CORS requests.* <p>The special value {@code "*"} allows all headers to be exposed for* non-credentialed requests.* <p>By default no headers are listed as exposed.*/String[] exposedHeaders() default {};/*** The list of supported HTTP request methods.* <p>By default the supported methods are the same as the ones to which a* controller method is mapped.*/RequestMethod[] methods() default {};/*** Whether the browser should send credentials, such as cookies along with* cross domain requests, to the annotated endpoint. The configured value is* set on the {@code Access-Control-Allow-Credentials} response header of* preflight requests.* <p><strong>NOTE:</strong> Be aware that this option establishes a high* level of trust with the configured domains and also increases the surface* attack of the web application by exposing sensitive user-specific* information such as cookies and CSRF tokens.* <p>By default this is not set in which case the* {@code Access-Control-Allow-Credentials} header is also not set and* credentials are therefore not allowed.*/String allowCredentials() default "";/*** The maximum age (in seconds) of the cache duration for preflight responses.* <p>This property controls the value of the {@code Access-Control-Max-Age}* response header of preflight requests.* <p>Setting this to a reasonable value can reduce the number of preflight* request/response interactions required by the browser.* A negative value means <em>undefined</em>.* <p>By default this is set to {@code 1800} seconds (30 minutes).*/long maxAge() default -1;總結
以上是生活随笔為你收集整理的Springboot 解决跨域的四种姿势的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用Docker Compose安装my
- 下一篇: 雷军做程序员时写的博客,太牛了。。