Java springboot跨域
时间: 2023-08-29 14:11:02 浏览: 213
在Java Spring Boot中解决跨域问题可以通过以下几个步骤实现:
1. 添加CORS配置:在你的Spring Boot应用程序的配置类或者Web配置类中,添加一个CORS配置。你可以使用`@CrossOrigin`注解来实现全局的CORS配置,或者使用`CorsRegistry`来配置CORS规则。例如:
```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 WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:8080") // 允许的前端域名
.allowedMethods("GET", "POST", "PUT", "DELETE") // 允许的请求方法
.allowedHeaders("*") // 允许的请求头
.allowCredentials(true); // 是否允许发送 Cookie
}
}
```
2. 配置跨域过滤器:如果你不想使用全局的CORS配置,你可以通过配置一个跨域过滤器来实现。创建一个类实现`javax.servlet.Filter`接口,并在`doFilter`方法中设置响应头信息来允许跨域请求。例如:
```java
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
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 {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setHeader("Access-Control-Allow-Origin", "http://localhost:8080");
httpResponse.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
httpResponse.setHeader("Access-Control-Allow-Headers", "*");
httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
chain.doFilter(request, response);
}
}
```
3. 注册跨域过滤器:在你的应用程序配置中注册跨域过滤器。例如,在Spring Boot的主类中添加以下代码:
```java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class YourApplication {
public static void main(String[] args) {
SpringApplication.run(YourApplication.class, args);
}
@Bean
public FilterRegistrationBean<CorsFilter> corsFilter() {
FilterRegistrationBean<CorsFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new CorsFilter());
registrationBean.setOrder(0); // 设置过滤器优先级
return registrationBean;
}
阅读全文