

下载本文档
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
java,SpringBootHTTP接⼝跨域调⽤及⽩名单实现背景系统之前为⼀个单页应⽤提供过Rest接⼝,部署时这个单页应⽤与系统不在同⼀域内,出现跨域⽆法访问的问题。Spring从4.2版本开始提供了@CrossOrigin注解,让这个问题的解决变得⾮常简单。实现⼀⾸先看下@CrossOrigin的源码(删掉了开头的部分注释):packageorg.springframework.web.bind.annotation;importjava.lang.annotation.Documented;importjava.lang.annotation.ElementType;importjava.lang.annotation.Retention;importjava.lang.annotation.RetentionPolicy;importjava.lang.annotation.Target;importorg.springframework.core.annotation.AliasFor;importorg.springframework.web.cors.CorsConfiguration;/***@authorRussellAllen*@authorSebastienDeleuze*@authorSamBrannen*@since4.2*/@Target({ElementType.METHOD,ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic@interfaceCrossOrigin{/***@deprecatedasofSpring4.3.4,infavorofusing{@linkCorsConfiguration#applyPermitDefaultValues}*/@DeprecatedString[]DEFAULT_ORIGINS={"*"};/***@deprecatedasofSpring4.3.4,infavorofusing{@linkCorsConfiguration#applyPermitDefaultValues}*/@DeprecatedString[]DEFAULT_ALLOWED_HEADERS={"*"};/***@deprecatedasofSpring4.3.4,infavorofusing{@linkCorsConfiguration#applyPermitDefaultValues}*/@DeprecatedbooleanDEFAULT_ALLOW_CREDENTIALS=true;/***@deprecatedasofSpring4.3.4,infavorofusing{@linkCorsConfiguration#applyPermitDefaultValues}*/@DeprecatedlongDEFAULT_MAX_AGE=1800;/***Aliasfor{@link#origins}.*/@AliasFor("origins")String[]value()default{};/***Listofallowedorigins,e.g.{@code""}.*Thesevaluesareplacedinthe{@codeAccess-Control-Allow-Origin}*headerofboththepre-flightresponseandtheactualresponse.*{@code"*"}meansthatalloriginsareallowed.*Ifundefined,alloriginsareallowed.*@see#value*/@AliasFor("value")String[]origins()default{};/***Listofrequestheadersthatcanbeusedduringtheactualrequest.*Thispropertycontrolsthevalueofthepre-flightresponse's*{@codeAccess-Control-Allow-Headers}header.*{@code"*"}meansthatallheadersrequestedbytheclientareallowed.*Ifundefined,allrequestedheadersareallowed.*/String[]allowedHeaders()default{};/***Listofresponseheadersthattheuser-agentwillallowtheclienttoaccess.*Thispropertycontrolsthevalueofactualresponse's*{@codeAccess-Control-Expose-Headers}header.*Ifundefined,anemptyexposedheaderlistisused.*/String[]exposedHeaders()default{};/***ListofsupportedHTTPrequestmethods,e.g.*{@code"{RequestMethod.GET,RequestMethod.POST}"}.*Methodsspecifiedhereoverridethosespecifiedvia{@codeRequestMapping}.*Ifundefined,methodsdefinedby{@linkRequestMapping}annotation*areused.*/RequestMethod[]methods()default{};/***Whetherthebrowsershouldincludeanycookiesassociatedwiththe*domainoftherequestbeingannotated.*Setto{@code"false"}ifsuchcookiesshouldnotincluded.undefined*Anemptystring({@code""})means.*{@code"true"}meansthatthepre-flightresponsewillincludetheheader*{@codeAccess-Control-Allow-Credentials=true}.*Ifundefined,credentialsareallowed.*/StringallowCredentials()default"";/***Themaximumage(inseconds)ofthecachedurationforpre-flightresponses.*Thispropertycontrolsthevalueofthe{@codeAccess-Control-Max-Age}*headerinthepre-flightresponse.*Settingthistoareasonablevaluecanreducethenumberofpre-flight*request/responseinteractionsrequiredbythebrowser.undefined*Anegativevaluemeans*.Ifundefined,maxageissetto{@code1800}seconds(i.e.,30minutes).*/longmaxAge()default-1;}从上⾯源码中可以看到,@CrossOrigin注解⽀持⽤于类和⽅法,访问IP默认为不限制,预检请求的有效期默认为1800秒,所以如不需指定IP和有效期,直接给需要⽀持跨域的类或⽅法添加注解即可:@CrossOriginpublicJSONObjectmyMethod(...){...}但是事情肯定不会这么简单。。。实现⼆真正的需求是要通过配置⽂件配置IP⽩名单,⽩名单内允许跨域访问。然鹅,由于注解的参数⽆法动态赋值,IP地址这种参数也不能硬编码,所以@CrossOrigin就被我⽆情的抛弃了,转⽽通过Filter来实现:importorg.springframework.beans.factory.annotation.Value;importorg.springframework.boot.web.servlet.ServletComponentScan;importorg.springframework.stereotype.Component;importjavax.servlet.Filter;importjavax.servlet.FilterChain;importjavax.servlet.FilterConfig;importjavax.servlet.ServletException;importjavax.servlet.ServletRequest;importjavax.servlet.ServletResponse;importjavax.servlet.annotation.WebFilter;importjavax.servlet.http.HttpServletResponse;importjava.io.IOException;@Component@ServletComponentScan@WebFilter(urlPatterns="/*",filterName="domainFilter")publicclassDomainFilterimplementsFilter{@Value("${allow-origin}")privateStringdomain;@Overridepublicvoidinit(FilterConfigfilterConfig)throwsServletException{}@OverridepublicvoiddoFilter(ServletRequestservletRequest,ServletResponseservletResponse,FilterChainfilterChain)throwsIOException,ServletException{HttpServletResponseresponse=(HttpServletResponse)servletResponse;if(!domain.startsWith("http://")&&!domain.startsWith("https://")){domain="http://"+domain;}response.setHeader("Access-Control-Allow-Origin",domain);response.setHeader("Access-Control-Allow-Methods","POST,GET,OPTIONS,DELETE");response.setHeader("Access-Control-Max-Age",
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 机电设备维修技术 第3版 课件 第六章-典型机电设备的维修
- 单片机课程设计心得体会模版
- 湖北省襄阳市宜城市五校2024-2025学年七年级下学期期中学业质量监测历史试卷(含答案)
- 北京版英语Unit 4 Where is my shirt《Lesson 13》课件
- 公司采购员年终总结模版
- 2023年雷雨知识竞赛题目及答案
- 山西科技学院《光学基础实验(二)》2023-2024学年第二学期期末试卷
- 市场营销营销策略知识点习题
- 打桩工程分包合同
- 江西省永新县达标名校2025年初三下学期七调考试语文试题含解析
- 2025年部编版新教材语文一年级下册期末测试题及答案(一)
- (统编2024版)语文一年级下册第三单元解析+任务目标+大单元教学设计
- 内河船舶船员基本安全知识考试题库300题(含答案)
- 校长论坛交流发言:引领教师专业成长的核心能力点燃教育变革的引擎
- 2024 年普通高等学校招生全国统一考试新课标 I 卷-数学试卷-全国
- 《春夏中医养生》课件
- 2024年02月北京2024年北京银行总行社会招考(217)笔试历年参考题库附带答案详解
- 《高速公路设计审查技术指南》
- 燃气岗位安全培训
- 《pmp项目管理培训》课件
- 机械设计基础B知到智慧树章节测试课后答案2024年秋哈尔滨工程大学
评论
0/150
提交评论