前言 Springboot解决跨域的四种姿势姿势一 实现WebMvcConfigureraddCorsMappings的方法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();}}姿势二 重新注入CorsFilterimportorg。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{开启跨域访问拦截器date20214299:50BeanpublicCorsFiltercorsFilter(){创建CorsConfiguration对象后添加配置CorsConfigurationcorsConfigurationnewCorsConfiguration();设置放行哪些原始域corsConfiguration。addAllowedOrigin();放行哪些原始请求头部信息corsConfiguration。addAllowedHeader();放行哪些请求方式corsConfiguration。addAllowedMethod();UrlBasedCorsConfigurationSourcesourcenewUrlBasedCorsConfigurationSource();2。添加映射路径source。registerCorsConfiguration(,corsConfiguration);returnnewCorsFilter(source);}}姿势三 创建一个filter解决跨域Slf4jComponentWebFilter(urlPatterns{},filterNameheaderFilter)publicclassHeaderFilterimplementsFilter{OverridepublicvoiddoFilter(ServletRequestrequest,ServletResponseresp,FilterChainchain)throwsIOException,ServletException{HttpServletResponseresponse(HttpServletResponse)resp;解决跨域访问报错response。setHeader(AccessControlAllowOrigin,);response。setHeader(AccessControlAllowMethods,POST,PUT,GET,OPTIONS,DELETE);设置过期时间response。setHeader(AccessControlMaxAge,3600);response。setHeader(AccessControlAllowHeaders,Origin,XRequestedWith,ContentType,Accept,clientid,uuid,Authorization);支持HTTP1。1。response。setHeader(CacheControl,nocache,nostore,mustrevalidate);支持HTTP1。0。response。setHeader(Expires,0);response。setHeader(Pragma,nocache);编码response。setCharacterEncoding(UTF8);chain。doFilter(request,resp);}Overridepublicvoidinit(FilterConfigfilterConfig){log。info(跨域过滤器启动);}Overridepublicvoiddestroy(){log。info(跨域过滤器销毁);}}姿势四 使用CrossOrigin注解 可以使用在单个方法上也可以使用在类上Target({ElementType。TYPE,ElementType。METHOD})Retention(RetentionPolicy。RUNTIME)DocumentedpublicinterfaceCrossOrigin{deprecatedasofSpring5。0,infavorof{linkCorsConfigurationapplyPermitDefaultValues}DeprecatedString〔〕DEFAULTORIGINS{};deprecatedasofSpring5。0,infavorof{linkCorsConfigurationapplyPermitDefaultValues}DeprecatedString〔〕DEFAULTALLOWEDHEADERS{};deprecatedasofSpring5。0,infavorof{linkCorsConfigurationapplyPermitDefaultValues}DeprecatedbooleanDEFAULTALLOWCREDENTIALSfalse;deprecatedasofSpring5。0,infavorof{linkCorsConfigurationapplyPermitDefaultValues}DeprecatedlongDEFAULTMAXAGE1800;Aliasfor{linkorigins}。AliasFor(origins)String〔〕value()default{};Alistoforiginsforwhichcrossoriginrequestsareallowed。Please,see{linkCorsConfigurationsetAllowedOrigins(List)}fordetails。pBydefaultalloriginsareallowedunless{codeoriginPatterns}isalsosetinwhichcase{codeoriginPatterns}isusedinstead。AliasFor(value)String〔〕origins()default{};Alternativeto{linkorigins()}thatsupportsoriginsdeclaredviawildcardpatterns。Please,seelinkCorsConfigurationsetAllowedOriginPatterns(List)}fordetails。pBydefaultthisisnotset。since5。3String〔〕originPatterns()default{};Thelistofrequestheadersthatarepermittedinactualrequests,possibly{code}toallowallheaders。pAllowedheadersarelistedinthe{codeAccessControlAllowHeaders}responseheaderofpreflightrequests。pAheadernameisnotrequiredtobelistedifitisoneof:{codeCacheControl},{codeContentLanguage},{codeExpires},{codeLastModified},or{codePragma}aspertheCORSspec。pBydefaultallrequestedheadersareallowed。String〔〕allowedHeaders()default{};TheListofresponseheadersthattheuseragentwillallowtheclienttoaccessonanactualresponse,otherthansimpleheaders,i。e。{codeCacheControl},{codeContentLanguage},{codeContentType},{codeExpires},{codeLastModified},or{codePragma},pExposedheadersarelistedinthe{codeAccessControlExposeHeaders}responseheaderofactualCORSrequests。pThespecialvalue{code}allowsallheaderstobeexposedfornoncredentialedrequests。pBydefaultnoheadersarelistedasexposed。String〔〕exposedHeaders()default{};ThelistofsupportedHTTPrequestmethods。pBydefaultthesupportedmethodsarethesameastheonestowhichacontrollermethodismapped。RequestMethod〔〕methods()default{};Whetherthebrowsershouldsendcredentials,suchascookiesalongwithcrossdomainrequests,totheannotatedendpoint。Theconfiguredvalueissetonthe{codeAccessControlAllowCredentials}responseheaderofpreflightrequests。pstrongNOTE:strongBeawarethatthisoptionestablishesahighleveloftrustwiththeconfigureddomainsandalsoincreasesthesurfaceattackofthewebapplicationbyexposingsensitiveuserspecificinformationsuchascookiesandCSRFtokens。pBydefaultthisisnotsetinwhichcasethe{codeAccessControlAllowCredentials}headerisalsonotsetandcredentialsarethereforenotallowed。StringallowCredentials()default;Themaximumage(inseconds)ofthecachedurationforpreflightresponses。pThispropertycontrolsthevalueofthe{codeAccessControlMaxAge}responseheaderofpreflightrequests。pSettingthistoareasonablevaluecanreducethenumberofpreflightrequestresponseinteractionsrequiredbythebrowser。Anegativevaluemeansemundefinedem。pBydefaultthisissetto{code1800}seconds(30minutes)。longmaxAge()default1; 最后 全套的Java面试宝典手册:性能调优微服务架构并发编程开源框架分布式等七大面试专栏,包含Tomcat、JVM、MySQL、SpringCloud、SpringBoot、Dubbo、并发、Spring、SpringMVC、MyBatis、Zookeeper、Ngnix、Kafka、MQ、Redis、MongoDB、memcached等等。如果你对这个感兴趣,小编可免费分享。 已到金九的末尾,还想再战银十?那便可先来刷刷这份283页的秋招JAVA面试手册! 资料获取方式:关注小编转发文章私信【面试题】获取上述资料 资料获取方式:关注小编转发文章私信【面试题】获取上述资料 资料获取方式:关注小编转发文章私信【面试题】获取上述资料