基于SpringBoot解决歌珥跨域问题的示例分析

  介绍

这篇文章主要介绍了基于SpringBoot解决歌珥跨域问题的示例分析,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获、下面让小编带着大家一起了解一下。

一、关于跨域介绍

在前后分离的架构下,跨域问题难免会遇见比如,站点http://domain-a.com的某HTML页面通过的src请求http://domain-b.com/image.jpg。

网络上的许多页面都会加载来自不同域的CSS样式表,图像和脚本等资源。

出于安全原因,浏览器限制从脚本内发起的跨源HTTP请求。

例如,XMLHttpRequest API和取回遵循同源策略。

这意味着使用这些API的Web应用程序只能从加载应用程序的同一个域请求HTTP资源,除非使用歌珥头文件。

跨域的体现,在于它的域名不同或者端口不同,但要注意以下的形式为非跨域模式

http://www.yisu.com/index.html==比;http://www.yisu.com/login.html

二、弹簧引导跨域(@CrossOrigin)

当然这里虽然指SpringBoot但是SpringMVC也是一样的,要求在Spring4.2及以上的版本

1, @CrossOrigin使用场景要求

Spring4.2 jdk1.8 + +

2, @CrossOrigin源码解析(翻译参考网络,文末列出参考地址)

@Target ({ElementType.METHOD的不同之处是,ElementType.TYPE })   @Retention (RetentionPolicy.RUNTIME)   @Documented   public  @interface  CrossOrigin  {   String[],才能DEFAULT_ORIGINS =, {,“*”,};   String[],才能DEFAULT_ALLOWED_HEADERS =, {,“*”,};   boolean 才能;DEFAULT_ALLOW_CREDENTIALS =,真的;   long 才能;DEFAULT_MAX_AGE =, 1800;   ,/* *   ,,*,同属起源性一样   ,,*/@AliasFor才能(“origins")   String[],才能值(),default  {};   ,/* *   ,,*,所有支持域的集合,例如“http://domain1.com"。   ,,*,& lt; p>这些值都显示在请求头中的Access-Control-Allow-Origin   ,,*,“*“代表所有域的请求都支持   ,,*,& lt; p>如果没有定义,所有请求的域都支持   ,,*,@see  #价值   ,,*/@AliasFor才能(“value")   ,,String[],起源(),default  {};   ,/* *   ,,*,允许请求头重的头,默认都支持   ,,*/String[],才能allowedHeaders (), default  {};   ,/* *   ,,*,响应头中允许访问的头,默认为空   ,,*/String[],才能exposedHeaders (), default  {};   ,/* *   ,,*,请求支持的方法,例如“{RequestMethod.GET, RequestMethod.POST}“}。   ,,*,默认支持RequestMapping中设置的方法   ,,*/RequestMethod才能[],()方法,default  {};   ,/* *   ,,*,是否允许饼干随请求发送,使用时必须指定具体的域   ,,*/String 才能;allowCredentials (), default ““;   ,/* *   ,,*,预请求的结果的有效期,默认30分钟   ,,*/long 才能;maxAge (), default  1;   }

3, @CrossOrigin使用

弹簧引导下的请求处理控制器

package  com.example.demo.controller;   import  com.example.demo.domain.User;   import  com.example.demo.service.IUserFind;   import  org.springframework.web.bind.annotation.CrossOrigin;   import  org.springframework.web.bind.annotation.GetMapping;   import  org.springframework.web.bind.annotation.RequestParam;   import  org.springframework.web.bind.annotation.RestController;   import  javax.annotation.Resource;/* *   ,* @Title:用户控件   ,* @ProjectName 演示   ,* @Description:请求处理控制器   ,* @author 浅然   ,* @date  2018/7/2022:18   * */@RestController//实现跨域注解//起源=?“代表所有域名都可访问//maxAge飞行前响应的缓存持续时间的最大年龄,简单来说就是饼干的有效期,单位为秒//若maxAge是负数,则代表为临时饼干,不会被持久化,饼干信息保存在浏览器内存中,浏览器关闭饼干就消失   @CrossOrigin (=origins “*“, maxAge =, 3600)   public  class  UserController  {   ,@   private 才能;IUserFind  userFind;   @GetMapping才能(“finduser")   public 才能;User  finduser (@RequestParam (value=https://www.yisu.com/zixun/癷d”)整数id) {//此处省略相应代码   }   }

后台返回的数据

基于SpringBoot解决歌珥跨域问题的示例分析

前端跨域请求

& lt; ! DOCTYPE  html>   & lt; html>   ,& lt; head>   ,& lt; meta  charset=皍tf-8",/比;   ,& lt; title> demo

基于SpringBoot解决歌珥跨域问题的示例分析