第04章 Spring-Boot CORS跨域处理

第04章 Spring-Boot CORS跨域处理

前言

  • 为什么要使用 Spring-Boot?

    可参考官方文档。

  • 什么是 Spring-Boot?

    可参考官方文档说明。

  • 官方地址

    https://spring.io/projects/spring-boot

目标

  • 完成 Jenkins 在 Docker 中的安装与配置。
  • 安装在 Docker 中的 Jenkins 能正常对外提供服务。
  • 在外部开发环境中能正常访问和使用 Jenkins 持续集成服务。

环境

  • **VMware:**VMware Workstation 14 Pro

  • **Linux:**CentOS7.4

  • **Docker:**18.06.0-ce, build 0ffa825

  • **Jenkins:**Jenkins2.121.1

  • **JDK:**jdk1.8.0_172

  • **Spring-Boot:**2.0.4

  • **Eclipse:**Eclipse Neon.3 (4.6.3)

  • spring-tool-suite:

    Version: 3.8.4.RELEASE
    Build Id: 201703310825
    Platform: Eclipse Neon.3 (4.6.3)

  • **Maven:**3.5.0

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

CORS 与 JSONP 相比

1、 JSONP 只能实现 GET 请求,而 CORS 支持所有类型的 HTTP 请求。

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

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

Chrome 3+

Firefox 3.5+

Opera 12+

Safari 4+

Internet Explorer 8+

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

全局配置

@Configuration
public class CorsConfigurer implements WebMvcConfigurer {
    
    

	@Override
	public void addCorsMappings(CorsRegistry registry) {
    
    
		// 限制了路径和域名的访问,指定域名可跨域,不指定就允许所有都可以跨域
		registry.addMapping("/cors/**").allowedOrigins("http://localhost:8080");
	}

}

全局跨域 Controller

@RestController
@RequestMapping("/cors")
public class CorsController {
    
    
    @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;
    }
}

定义方法级跨域 Controller

@RestController
@RequestMapping(value = "/cors", method = RequestMethod.POST)
public class CorsController {
    
    
	/*
	 *  通过使用注解@CrossOrigin,进行方法级细粒度跨域配置。
	 *  在某个方法上加这个注释就可以不用定义跨域配置
	 *  需要启动两个服务进行测试
	 */
	@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;
	}
}

测试跨域访问,在一个需要跨域的应用页面中加上这段代码用于跨域测试

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

et",
type: “POST”,
data: {
name: “测试”
},
success: function(data, status, xhr) {
console.log(data);
alert(data.name);
}
});


猜你喜欢

转载自blog.csdn.net/pointdew/article/details/108541389