当前位置: 移动技术网 > IT编程>开发语言>Java > Spring Boot Web应用开发 CORS 跨域请求支持

Spring Boot Web应用开发 CORS 跨域请求支持

2019年07月22日  | 移动技术网IT编程  | 我要评论

一、web开发经常会遇到跨域问题,解决方案有:jsonp,iframe,cors等等

cors与jsonp相比

1、 jsonp只能实现get请求,而cors支持所有类型的http请求。

2、 使用cors,开发者可以使用普通的xmlhttprequest发起请求和获得数据,比起jsonp有更好的错误处理。

3、 jsonp主要被老的浏览器支持,它们往往不支持cors,而绝大多数现代浏览器都已经支持了cors

浏览器支持情况

  1. chrome 3+
  2. firefox 3.5+
  3. opera 12+
  4. safari 4+
  5. internet explorer 8+

 二、在spring mvc 中可以配置全局的规则,也可以使用@crossorigin注解进行细粒度的配置。 

全局配置:

@configuration
public class customcorsconfiguration {
 
 @bean
 public webmvcconfigurer corsconfigurer() {
  return new webmvcconfigureradapter() {
     @override
     public void addcorsmappings(corsregistry registry) {
       registry.addmapping("/api/**").allowedorigins("http://localhost:8080");
     }
  };
 }
}

或者是

/**
 * 全局设置
 *
 * @author wujing
 */
@configuration
public class customcorsconfiguration2 extends webmvcconfigureradapter {
 
 @override
 public void addcorsmappings(corsregistry registry) {
  registry.addmapping("/api/**").allowedorigins("http://localhost:8080");
 }
}

定义方法:

/**
 * @author wujing
 */
@restcontroller
@requestmapping("/api")
public class apicontroller {
 
 @requestmapping(value = "/get")
 public hashmap<string, object> get(@requestparam string name) {
  hashmap<string, object> map = new hashmap<string, object>();
  map.put("title", "hello world");
  map.put("name", name);
  return map;
 }
}

测试js:

$.ajax({
          url: "http://localhost:8081/api/get",
        type: "post",
        data: {
          name: "测试"
        },
        success: function(data, status, xhr) {
          console.log(data);
          alert(data.name);
        }
       });

细粒度配置

 /**
 * @author wujing
 */
@restcontroller
@requestmapping(value = "/api", method = requestmethod.post)
public class apicontroller {
 
 @crossorigin(origins = "http://localhost:8080")
 @requestmapping(value = "/get")
 public hashmap<string, object> get(@requestparam string name) {
  hashmap<string, object> map = new hashmap<string, object>();
  map.put("title", "hello world");
  map.put("name", name);
  return map;
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网