springboot项目 解决跨域问题有哪些方式 实现代码
时间: 2023-08-06 21:05:02 浏览: 108
在Spring Boot项目中,解决跨域问题有以下几种方式:
1. 使用@CrossOrigin注解
可以在Controller的方法上添加@CrossOrigin注解实现跨域请求。例如:
```
@CrossOrigin(origins = "http://localhost:8080")
@GetMapping("/hello")
public String hello() {
return "Hello World!";
}
```
2. 使用WebMvcConfigurer配置类
可以通过WebMvcConfigurer配置类来实现跨域请求。例如:
```
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowCredentials(true)
.maxAge(3600);
}
}
```
3. 使用Filter过滤器
可以通过Filter过滤器来实现跨域请求。例如:
```
@Component
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
response.setHeader("Access-Control-Allow-Credentials", "true");
chain.doFilter(req, res);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
}
```
注意:以上代码仅供参考,实际使用需要根据具体情况进行调整。
阅读全文