同源策略
浏览器采用了同源策略,只有位于相同域中的其它页面才访问这些数据。
1、协议:协议必须匹配。如果在以httpd起始的页面上保存了数据,那么此数据就无法通过https来访问。
2、子域名:子域名必须匹配。例如maps.google.com无法访问www.google.com上存储的数据。
3、域名:域名必须匹配。如例如google不能访问baidu.com上存储的数据。
4、端口号:端口号必须匹配。web服务器可以指定各种端口号。URL中通常不指定端口号,默认使用80端口。
跨来源资源共享
与同源策略相反的是跨来源资源共享。
跨来源资源共享(CORS),亦译为跨域资源共享,是一份浏览器技术的规范,提供了 Web 服务从不同网域传来沙盒脚本的方法,以避开浏览器的同源策略。
来用跨来源资源共享可以解决同源策略产生的问题。
主要从两个方面来解决:一是服务端,二是客户端。
服务端有servlet jersey spring,分别有不同的解决方案。
servlet在过滤中添加以下代码
1
2
3
4
5
6
7
8
9
10
|
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; // Authorize (allow) all domains to consume the content ((HttpServletResponse) servletResponse).addHeader( "Access-Control-Allow-Origin" , "*" ); ((HttpServletResponse) servletResponse).addHeader( "Access-Control-Allow-Methods" , "GET, OPTIONS, HEAD, PUT, POST" ); } |
jersey创建一个过滤器,添加以下代码
1
2
3
4
5
6
7
8
9
|
public class CorsFilter implements ContainerResponseFilter { @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { // 注意,添加的头是小写哦 responseContext.getHeaders().add( "access-control-allow-origin" , " * " ); } } |
spring 最简洁,只要在方法上添加注释@CrossOrigin
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
@RestController public class StudentController { @Autowired StudentRepository studentRepository; @CrossOrigin @PostMapping (value= "/students" ,consumes = "application/json" ) public ResponseEntity<Object> createStudent( @RequestBody Student student) { Student savedStudent = studentRepository.save(student); URI location = ServletUriComponentsBuilder.fromCurrentRequest().path( "/{id}" ) .buildAndExpand(savedStudent.getId()).toUri(); return ResponseEntity.created(location).build(); } } |
客户端调用时,添加一个配置参数crossDomain: true
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
$obj= '{"name":"gt","age":22}' ; $.ajax({ cache: false , crossDomain: true , type: "POST" , dataType: "json" , contentType: "application/json" , data:$obj, success: function (data) { console.log(data); } }); |