当前位置: 移动技术网 > IT编程>开发语言>Java > 使用Spring CROS解决项目中的跨域问题详解

使用Spring CROS解决项目中的跨域问题详解

2020年03月09日  | 移动技术网IT编程  | 我要评论

cros(cross-origin resource sharing) 用于解决浏览器中跨域请求的问题。简单的get请求可以使用jsonp来解决,而对于其它复杂的请求则需要后端应用的支持cros。spring在4.2版本之后提供了@crossorigin 注解来实现对cross的支持。

在controller方法上配置

@crossorigin(origins = {"http://loaclhost:8088"})
@requestmapping(value = "/crosstest",method = requestmethod.get)
public string greeting() {
  return "corss test";
}

在controller上配置,那么这个controller中的所有方法都会支持cors

import org.springframework.stereotype.controller;
import org.springframework.web.bind.annotation.crossorigin;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestmethod;

@crossorigin(origins = "http://localhost:8088",maxage = 3600)
@controller
@requestmapping("/api")
public class appcontroller {
  
    @requestmapping(value = "/crosstest",method = requestmethod.get)
    public string greeting() {
      return "corss test";
    }
    
}

java config全局配置

import org.springframework.context.annotation.configuration;
import org.springframework.web.servlet.config.annotation.corsregistry;
import org.springframework.web.servlet.config.annotation.enablewebmvc;
import org.springframework.web.servlet.config.annotation.webmvcconfigureradapter;

@configuration
@enablewebmvc
public class springwebconfig extends webmvcconfigureradapter {

  /**
   * {@inheritdoc}
   * <p>this implementation is empty.
   *
   * @param registry
   */
  @override
  public void addcorsmappings(corsregistry registry) {
    super.addcorsmappings(registry);
    // 对所有的url配置
    registry.addmapping("/**");

    // 针对某些url配置
    registry.addmapping("/api/**").allowedorigins("http:///localhost:8088")
        .allowedmethods("put","delete")
        .allowedheaders("header1","header2","header3")
        .exposedheaders("header1","header2")
        .allowcredentials(false).maxage(3600);
  }
}

xml全局配置

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemalocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd">

  <mvc:cors>
    <!--<mvc:mapping path=""/>-->
    <mvc:mapping path="/api/**"
           allowed-origins="http://localhost:8088,http://localhost:8888"
           allowed-methods="get,put"
           allowed-headers="header1,header2"
           exposed-headers="header1,header2"
           allow-credentials="false"
           max-age="3600" />
  </mvc:cors>
</beans>

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

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

相关文章:

验证码:
移动技术网