在Spring Boot中处理跨域请求可以通过以下几种方式实现:
1. 使用注解 `@CrossOrigin`:可以在控制器类或者具体的请求处理方法上添加`@CrossOrigin`注解来启用跨域支持。例如:
```java
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@CrossOrigin(origins = "http://example.com")
public class MyController {
@GetMapping("/hello")
public String hello() {
return "Hello, world!";
}
}
```
在上面的示例中,`@CrossOrigin(origins = "http://example.com")`指定了允许跨域访问的来源URL。
2. 配置全局跨域支持:可以通过创建一个配置类来配置全局的跨域支持。例如:
```java
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);
}
}
```
上述配置将允许来自`http://example.com`的跨域请求,并允许的HTTP方法为GET、POST、PUT和DELETE。
3. 使用过滤器(Filter):可以编写一个自定义的过滤器来处理跨域请求。通过过滤器,你可以在请求到达控制器之前进行跨域处理。例如:
```java
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.setHeader("Access-Control-Allow-Origin", "http://example.com");
response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
response.setHeader("Access-Control-Allow-Headers", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Max-Age", "3600");
filterChain.doFilter(servletRequest, servletResponse);
}
// 省略其他方法...
}
```
然后,在Spring Boot中注册这个过滤器:
```java
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public FilterRegistrationBean<CorsFilter> corsFilterRegistrationBean() {
FilterRegistrationBean<CorsFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new CorsFilter());
registrationBean.addUrlPatterns("/*");
registrationBean.setOrder(1);
return registrationBean;
}
}
```