一、配置过滤器
1. 编写过滤器类
import org.springframework.core.annotation.Order;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Order(1) //如有多个过滤器,配置过滤器的顺序
@WebFilter(urlPatterns = "/*",filterName = "CorsFilter") //urlPatterns 配置为哪些请求实现过滤,filterName 为过滤器起名为“ParamsFilter”
public class CrossOriginFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
//filter对象只会创建一次,init方法也只会执行一次。
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletResponse resp = (HttpServletResponse) response;
resp.addHeader("Access-Control-Allow-Credentials", "true");
resp.addHeader("Access-Control-Allow-Origin", "*");
resp.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
resp.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN");
chain.doFilter(request, resp);
}
@Override
public void destroy() {
//在销毁Filter时自动调用(程序关闭或者主动销毁Filter)。
}
}
2. 启动类扫描过滤器
//如果Application类和Servlet类不在同一包下,则@ServletComponentScan需要添加相应的路径
@ServletComponentScan
@SpringBootApplication
public class PopkartApplication {
public static void main(String[] args) {
SpringApplication.run(PopkartApplication.class, args);
}
}
二、 配置类配置Cors的跨域
1. extends WebMvcConfigurerAdapter
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class CrossOriginConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "DELETE", "PUT")
.maxAge(3600);
}
}
2. implements WebMvcConfigurer
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("/**")
.allowCredentials(true) // 允许cookies跨域
.allowedOrigins("*") // 允许向该服务器提交请求的URI,*表示全部允许,在SpringMVC中,如果设成*,会自动转成当前请求头中的Origin
.allowedHeaders("*") // 允许访问的头信息,*表示全部
.allowedMethods("GET", "POST", "DELETE", "PUT") //允许的请求方法
.maxAge(18000L); // 预检请求的缓存时间(秒),即在这个时间段里,对于相同的跨域请求不会再预检了
}
}
补充:
SpringBoot升级2.4.0所出现的问题:
When allowCredentials is true, allowedOrigins cannot contain the special value "*“since that cannot be set on the “Access-Control-Allow-Origin” response header. To allow credentials to a set of origins, list them explicitly or consider using"allowedOriginPatterns” instead.
allowCredentials为true时,allowedOrigins不能包含特殊值“*”,因为不能在“Access Control Allow Origin”响应头上设置该值。要允许凭据指向一组源,请显式列出它们,或者考虑改用“allowedOriginPatterns”。
所以SpringBoot2.4.0以上版本要把.allowedOrigins("*")
换成.allowedOriginPatterns("*")
3. 创建Bean——CorsFilter
或CorsWebFilter
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CorsConfig {
/**
* attention:简单跨域就是GET,HEAD和POST请求,但是POST请求 的"Content-Type"只能是application/x-www-form-urlencoded, multipart/form-data 或 text/plain
* 反之,就是非简单跨域,此跨域有一个预检机制,说直白点,就是会发两次请求,一次OPTIONS请求,一次真正的请求
*/
@Bean
public CorsFilter corsFilter(){
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true); // 允许cookies跨域
config.addAllowedOrigin("*"); // 允许向该服务器提交请求的URI,*表示全部允许,在SpringMVC中,如果设成*,会自动转成当前请求头中的Origin
config.addAllowedHeader("*"); // 允许访问的头信息,*表示全部
config.setMaxAge(18000L); // 预检请求的缓存时间(秒),即在这个时间段里,对于相同的跨域请求不会再预检了
config.addAllowedMethod("OPTIONS"); // 允许提交请求的方法,*表示全部允许
config.addAllowedMethod("HEAD");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
config.addAllowedMethod("POST");
config.addAllowedMethod("DELETE");
config.addAllowedMethod("PATCH");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.cors.reactive.CorsWebFilter;
@Configuration
public class CorsConfig {
/**
* attention:简单跨域就是GET,HEAD和POST请求,但是POST请求 的"Content-Type"只能是application/x-www-form-urlencoded, multipart/form-data 或 text/plain
* 反之,就是非简单跨域,此跨域有一个预检机制,说直白点,就是会发两次请求,一次OPTIONS请求,一次真正的请求
*/
@Bean
public CorsWebFilter corsWebFilter(){
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true); // 允许cookies跨域
config.addAllowedOrigin("*"); // 允许向该服务器提交请求的URI,*表示全部允许,在SpringMVC中,如果设成*,会自动转成当前请求头中的Origin
config.addAllowedHeader("*"); // 允许访问的头信息,*表示全部
config.setMaxAge(18000L); // 预检请求的缓存时间(秒),即在这个时间段里,对于相同的跨域请求不会再预检了
config.addAllowedMethod("OPTIONS"); // 允许提交请求的方法,*表示全部允许
config.addAllowedMethod("HEAD");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
config.addAllowedMethod("POST");
config.addAllowedMethod("DELETE");
config.addAllowedMethod("PATCH");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return new CorsWebFilter(source);
}
}
三、在发生跨域的接口处添加@CrossOrigin注解
此方法适合跨域接口少时使用
@CrossOrigin详解
Spring 从4.2版本后开始支持 @CrossOrigin 注解实现跨域,这在一定程度上简化了我们实现跨域访问的开发成本,在需要跨域访问的方法或者类上加上这个注解便大功告成。
该注解可作用在类或方法上,默认情况下,@CrossOrigin允许在@RequestMapping注解中指定的所有源和HTTP方法
参数名 | 类型 | 说明 |
---|---|---|
value/origins | String[] | 允许来源域名的列表,例如 ‘www.baidu.com’,匹配的域名是跨域预请求 Response 头中的 ‘Access-Control-Aloow_origin’ 字段值。不设置确切值时默认支持所有域名跨域访问。 |
allowedHeaders | String[] | 跨域请求中允许的请求头中的字段类型, 该值对应跨域预请求 Response 头中的 ‘Access-Control-Allow-Headers’ 字段值。 不设置确切值默认支持所有的header字段(Cache-Controller、Content-Language、Content-Type、Expires、Last-Modified、Pragma)跨域访问。 |
exposedHeaders | String[] | 跨域请求请求头中允许携带的除Cache-Controller、Content-Language、Content-Type、Expires、Last-Modified、Pragma这六个基本字段之外的其他字段信息,对应的是跨域请求 Response 头中的 'Access-control-Expose-Headers’字段值。 |
methods | RequestMethod[] | 跨域HTTP请求中支持的HTTP请求类型(GET、POST、DELETE、PUT),不指定确切值时默认与 Controller 方法中的 methods 字段保持一致。 |
allowCredentials | String | 该值对应的是是跨域请求 Response 头中的 ‘Access-Control-Allow-Credentials’ 字段值。浏览器是否将本域名下的 cookie 信息携带至跨域服务器中。默认携带至跨域服务器中,但要实现 cookie 共享还需要前端在 AJAX 请求中打开 withCredentials 属性。 |
maxAge | long | 该值对应的是是跨域请求 Response 头中的 ‘Access-Control-Max-Age’ 字段值,表示预检请求响应的缓存持续的最大时间,目的是减少浏览器预检请求/响应交互的数量。默认值1800s。设置了该值后,浏览器将在设置值的时间段内对该跨域请求不再发起预请求。 |