跨域(Cross-Origin)是指在浏览器中,当一个网页的脚本试图访问不同源(域名、协议、端口)的资源时,就会发生跨域问题。同源策略是浏览器的一种安全机制,它限制了从一个源加载的文档或脚本如何与来自另一个源的资源进行交互。
以下情况会发生跨域问题:
1. 域名不同:如从www.example.com访问api.example.com,一个网页在域名为example.com的服务器上,而脚本试图访问域名为api.example.com的资源。
2. 协议不同:如从https://example.com访问http://example.com,一个网页使用https协议加载,而脚本试图访问使用http协议的资源。
3. 端口不同:如从localhost:3000访问localhost:4000,一个网页使用默认的8080端口加载,而脚本试图访问使用4000端口的资源。
示例1:
@RestController
@RequestMapping("/api")
public class UserController {
@CrossOrigin(origins = "http://example.com")
@GetMapping("/users")
public List<User> getUsers() {
// 返回用户列表
}
// 其他接口方法...
}
@CrossOrigin注解被添加到了getUsers()方法上。origins参数指定了允许跨域请求的来源,这里设置为"http://example.com",表示只允许来自该域的请求访问该接口。如果不指定origins参数,将允许所有来源的请求访问该接口。
@CrossOrigin注解也可以添加到类级别上,表示该类下的所有接口都允许跨域请求。例如:
@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "http://example.com")
public class UserController {
@GetMapping("/users")
public List<User> getUsers() {
// 返回用户列表
}
// 其他接口方法...
}
在这个示例中,UserController类下的所有接口都允许来自"http://example.com"域的跨域请求。
示例2:
通过实现WebMvcConfigurer接口来配置跨域访问
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://example.com")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("*")
.allowCredentials(true)
.maxAge(3600);
}
}
allowedOrigins("http://example.com"):指定允许访问的域名,这里只允许http://example.com域名访问。allowedMethods("GET", "POST", "PUT", "DELETE"):指定允许的HTTP请求方法。allowedHeaders("*"):指定允许的HTTP请求头。allowCredentials(true):指定是否允许发送Cookie等凭证信息。maxAge(3600):指定预检请求的有效期,单位为秒。通过以上配置,你的应用程序将只允许http://example.com域名进行跨域访问。
示例3:
继承WebMvcConfigurationSupport类并重写跨域方法
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@Configuration
public class CustomWebMvcConfiguration extends WebMvcConfigurationSupport {
@Override
protected void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*") // 允许所有来源
.allowedMethods("GET", "POST", "PUT", "DELETE") // 允许的请求方法
.allowedHeaders("*") // 允许所有请求头
.allowCredentials(true) // 允许发送凭据(如cookies)
.maxAge(3600); // 预检请求的有效期,单位为秒
}
}
.addMapping("/**")表示允许所有的URL路径进行跨域访问。.allowedOrigins("*")表示允许所有来源进行跨域访问。.allowedMethods("GET", "POST", "PUT", "DELETE")表示允许的请求方法。.allowedHeaders("*")表示允许所有请求头。.allowCredentials(true)表示允许发送凭据,如cookies。.maxAge(3600)表示预检请求的有效期为3600秒。注意,使用WebMvcConfigurationSupport类来自定义配置会覆盖Spring Boot的自动配置,因此需要谨慎使用。如果只需要简单的跨域配置,可以考虑使用@CrossOrigin注解来实现。