springboot 解决跨域
时间: 2023-09-13 18:07:24 浏览: 62
在Spring Boot中,可以通过以下几种方式解决跨域问题:
1. 使用注解 @CrossOrigin:可以在控制器类或者具体的请求处理方法上添加 @CrossOrigin 注解来允许跨域请求。例如,可以在控制器类上添加 @CrossOrigin(origins = "http://example.com"),指定允许来自"http://example.com"域的请求。
2. 使用配置文件:可以通过在配置文件中配置跨域相关属性来解决跨域问题。在application.properties或application.yml文件中添加以下配置:
```properties
# 允许跨域的域名
spring.mvc.allow-cors=true
spring.mvc.cors.allowed-origins=http://example.com
```
3. 自定义过滤器:可以编写一个自定义的过滤器,在过滤器中设置响应头信息来允许跨域请求。例如,创建一个名为CorsFilter的过滤器类,实现javax.servlet.Filter接口,并在doFilter方法中设置响应头:
```java
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setHeader("Access-Control-Allow-Origin", "http://example.com");
httpResponse.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
httpResponse.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
httpResponse.setHeader("Access-Control-Max-Age", "3600");
chain.doFilter(request, response);
}
}
```
然后,在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> corsFilter() {
FilterRegistrationBean<CorsFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new CorsFilter());
registrationBean.addUrlPatterns("/*");
return registrationBean;
}
}
```
以上是几种常用的解决跨域问题的方法。根据具体情况选择适合自己项目的方式进行配置和实现。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)