您的位置:首页 > 编程语言 > Java开发

【spring boot】2.0增加跨域请求支持 全局配置 以及局部配置

2018-03-27 10:43 1256 查看
一·简介
spring boot升级到2.0后发现继承WebMvcConfigurerAdapter实现跨域过时了,那我们就紧随潮流。
二·全局配置
2.0以前 支持跨域请求代码:import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
* 说明:跨域请求
*
* @author WangBin
* @version v1.0
* @date 2018/1/21/
*/
@Configuration
public class CorsConfig extends WebMvcConfigurerAdapter {

@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("*")
.maxAge(3600);
}
}2.0如下: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.WebMvcConfigurer;

/**
* 说明:跨域请求
*
* @author WangBin
* @version v1.0
* @date 2018/1/21/
*/
@Configuration
@EnableWebMvc
public class CorsConfig implements WebMvcConfigurer {

@Override
public void addCorsMappings(CorsRegistry registry) {
//设置允许跨域的路径
registry.addMapping("/**")
//设置允许跨域请求的域名
.allowedOrigins("*")
//是否允许证书 不再默认开启
.allowCredentials(true)
//设置允许的方法
.allowedMethods("*")
//跨域允许时间
.maxAge(3600);
}
}
三·局部配置示例
主要使用@CrossOrigin 注解,全局的配置 在@CrossOrigin里依旧可用
可以注解在单个方法上@RestController
@RequestMapping(/account)
public class AccountController {

@CrossOrigin
@GetMapping(/{id})
public Account retrieve(@PathVariable Long id) {

}

@DeleteMapping(/{id})
public void remove(@PathVariable Long id) {

}
}也可以注解在整个controller上@CrossOrigin(origins = http://domain2.com, maxAge = 3600)
@RestController
@RequestMapping(/account)
public class AccountController {

@GetMapping(/{id})
public Account retrieve(@PathVariable Long id) {

}

@DeleteMapping(/{id})
public void remove(@PathVariable Long id) {

}
}也可以解在整个controller上的同时注解在单个方法上@CrossOrigin(maxAge = 3600)
@RestController
@RequestMapping(/account)
public class AccountController {

@CrossOrigin(http://domain2.com)
@GetMapping(/{id})
public Account retrieve(@PathVariable Long id) {

}

@DeleteMapping(/{id})
public void remove(@PathVariable Long id) {

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息