首页>>后端>>SpringBoot->Spring boot解决跨域的四种解决方案

Spring boot解决跨域的四种解决方案

时间:2023-11-29 本站 点击:0

简介

跨域我就不多说了,我们今天开门见山直接解决跨域的几种解决方案,那就上方案

方案

方案一

实现WebMvcConfigurer#addCorsMappings的方法

importorg.springframework.context.annotation.Configuration;importorg.springframework.web.servlet.config.annotation.CorsRegistry;importorg.springframework.web.servlet.config.annotation.WebMvcConfigurer;@ConfigurationpublicclassCorsConfigimplementsWebMvcConfigurer{@OverridepublicvoidaddCorsMappings(CorsRegistryregistry){registry.addMapping("/**").allowedOrigins("*").allowedMethods("GET","HEAD","POST","PUT","DELETE","OPTIONS").allowCredentials(true).maxAge(3600).allowedHeaders("*");}}

方案二

重新注入CorsFilter

importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.web.cors.CorsConfiguration;importorg.springframework.web.cors.UrlBasedCorsConfigurationSource;importorg.springframework.web.filter.CorsFilter;/***解决跨域*/@ConfigurationpublicclassCorsFilterConfig{/***开启跨域访问拦截器**@date2021/4/299:50*/@BeanpublicCorsFiltercorsFilter(){//创建CorsConfiguration对象后添加配置CorsConfigurationcorsConfiguration=newCorsConfiguration();//设置放行哪些原始域corsConfiguration.addAllowedOrigin("*");//放行哪些原始请求头部信息corsConfiguration.addAllowedHeader("*");//放行哪些请求方式corsConfiguration.addAllowedMethod("*");UrlBasedCorsConfigurationSourcesource=newUrlBasedCorsConfigurationSource();//2.添加映射路径source.registerCorsConfiguration("/**",corsConfiguration);returnnewCorsFilter(source);}}

方案三

创建一个filter解决跨域

@Slf4j@Component@WebFilter(urlPatterns={"/*"},filterName="headerFilter")publicclassHeaderFilterimplementsFilter{@OverridepublicvoiddoFilter(ServletRequestrequest,ServletResponseresp,FilterChainchain)throwsIOException,ServletException{HttpServletResponseresponse=(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");//支持HTTP1.1.response.setHeader("Cache-Control","no-cache,no-store,must-revalidate");//支持HTTP1.0.response.setHeader("Expires","0");response.setHeader("Pragma","no-cache");//编码response.setCharacterEncoding("UTF-8");chain.doFilter(request,resp);}@Overridepublicvoidinit(FilterConfigfilterConfig){log.info("跨域过滤器启动");}@Overridepublicvoiddestroy(){log.info("跨域过滤器销毁");}}

方案四

使用CrossOrigin 注解

可以使用在单个方法上也可以使用在类上

Target({ElementType.TYPE,ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic@interfaceCrossOrigin{/**@deprecatedasofSpring5.0,infavorof{@linkCorsConfiguration#applyPermitDefaultValues}*/@DeprecatedString[]DEFAULT_ORIGINS={"*"};/**@deprecatedasofSpring5.0,infavorof{@linkCorsConfiguration#applyPermitDefaultValues}*/@DeprecatedString[]DEFAULT_ALLOWED_HEADERS={"*"};/**@deprecatedasofSpring5.0,infavorof{@linkCorsConfiguration#applyPermitDefaultValues}*/@DeprecatedbooleanDEFAULT_ALLOW_CREDENTIALS=false;/**@deprecatedasofSpring5.0,infavorof{@linkCorsConfiguration#applyPermitDefaultValues}*/@DeprecatedlongDEFAULT_MAX_AGE=1800;/***Aliasfor{@link#origins}.*/@AliasFor("origins")String[]value()default{};/***Alistoforiginsforwhichcross-originrequestsareallowed.Please,*see{@linkCorsConfiguration#setAllowedOrigins(List)}fordetails.*<p>Bydefaultalloriginsareallowedunless{@codeoriginPatterns}is*alsosetinwhichcase{@codeoriginPatterns}isusedinstead.*/@AliasFor("value")String[]origins()default{};/***Alternativeto{@link#origins()}thatsupportsoriginsdeclaredvia*wildcardpatterns.Please,see*@linkCorsConfiguration#setAllowedOriginPatterns(List)}fordetails.*<p>Bydefaultthisisnotset.*@since5.3*/String[]originPatterns()default{};/***Thelistofrequestheadersthatarepermittedinactualrequests,*possibly{@code"*"}toallowallheaders.*<p>Allowedheadersarelistedinthe{@codeAccess-Control-Allow-Headers}*responseheaderofpreflightrequests.*<p>Aheadernameisnotrequiredtobelistedifitisoneof:*{@codeCache-Control},{@codeContent-Language},{@codeExpires},*{@codeLast-Modified},or{@codePragma}aspertheCORSspec.*<p>Bydefaultallrequestedheadersareallowed.*/String[]allowedHeaders()default{};/***TheListofresponseheadersthattheuser-agentwillallowtheclient*toaccessonanactualresponse,otherthan"simple"headers,i.e.*{@codeCache-Control},{@codeContent-Language},{@codeContent-Type},*{@codeExpires},{@codeLast-Modified},or{@codePragma},*<p>Exposedheadersarelistedinthe{@codeAccess-Control-Expose-Headers}*responseheaderofactualCORSrequests.*<p>Thespecialvalue{@code"*"}allowsallheaderstobeexposedfor*non-credentialedrequests.*<p>Bydefaultnoheadersarelistedasexposed.*/String[]exposedHeaders()default{};/***ThelistofsupportedHTTPrequestmethods.*<p>Bydefaultthesupportedmethodsarethesameastheonestowhicha*controllermethodismapped.*/RequestMethod[]methods()default{};/***Whetherthebrowsershouldsendcredentials,suchascookiesalongwith*crossdomainrequests,totheannotatedendpoint.Theconfiguredvalueis*setonthe{@codeAccess-Control-Allow-Credentials}responseheaderof*preflightrequests.*<p><strong>NOTE:</strong>Beawarethatthisoptionestablishesahigh*leveloftrustwiththeconfigureddomainsandalsoincreasesthesurface*attackofthewebapplicationbyexposingsensitiveuser-specific*informationsuchascookiesandCSRFtokens.*<p>Bydefaultthisisnotsetinwhichcasethe*{@codeAccess-Control-Allow-Credentials}headerisalsonotsetand*credentialsarethereforenotallowed.*/StringallowCredentials()default"";/***Themaximumage(inseconds)ofthecachedurationforpreflightresponses.*<p>Thispropertycontrolsthevalueofthe{@codeAccess-Control-Max-Age}*responseheaderofpreflightrequests.*<p>Settingthistoareasonablevaluecanreducethenumberofpreflight*request/responseinteractionsrequiredbythebrowser.*Anegativevaluemeans<em>undefined</em>.*<p>Bydefaultthisissetto{@code1800}seconds(30minutes).*/longmaxAge()default-1;

以上Spring boot解决跨域的四种解决方案方案都学会了么?学会了三连哦!


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:/SpringBoot/345.html