SpringBoot解决跨域问题
创建一个filter解决跨域。
xxxxxxxxxx
1
2
public class SimpleCORSFilter implements Filter {
3
4
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
5
HttpServletResponse response = (HttpServletResponse) res;
6
response.setHeader("Access-Control-Allow-Origin", "*");
7
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, HEAD");
8
response.setHeader("Access-Control-Max-Age", "3600");
9
response.setHeader("Access-Control-Allow-Headers", "access-control-allow-origin, authority, content-type, version-info, X-Requested-With");
10
chain.doFilter(req, res);
11
}
12
13
public void init(FilterConfig filterConfig) {}
14
15
public void destroy() {}
16
}
基于WebMvcConfigurerAdapter配置加入Cors的跨域
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
public class CorsConfig extends WebMvcConfigurerAdapter {
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "DELETE", "PUT")
.maxAge(3600);
}
}
addMapping-----指哪些接口URL需要增加跨域设置allowedOrigins-----指的是前端哪些域名被允许跨域
allowedMethods-----指的是允许哪些方法
allowCredentials----因为自己项目需要带cookie等凭证,
使用注解@CrossOrigin(局部跨域)
("/shop")
()
public class ShopController {
("/")
public Map<String, Object> findAll() {
//返回数据
return DataSchool.getStudents();
}
}
其中@CrossOrigin中的2个参数:
origins : 允许可访问的域列表
maxAge:准备响应前的缓存持续的最大时间(以秒为单位)。
methods:请求的方法类型
第一种Filter的方案也支持springmvc。
第二、三种常用于springboot。