1. Filter configurationimport java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
/ * * * the ClassName: SimpleCORSFilter * Function: cross-domain *@version 1.0
* @sinceJDK 1.8 * /
@Component
public class SimpleCORSFilter implements Filter {
@Override
public void destroy(a) {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", request.getHeader("origin"));
//response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods"."POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age"."3600");
response.setHeader("Access-Control-Allow-Headers"."x-requested-with,Cache-Control,Pragma,Content-Type,Token");
response.setHeader("Access-Control-Allow-Credentials"."true");
chain.doFilter(req, res);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub}. 0The class configuration is provided aboveimport 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 {
private CorsConfiguration buildConfig(a) {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); / / 1
corsConfiguration.addAllowedHeader("*"); / / 2
corsConfiguration.addAllowedMethod("*"); / / 3
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter(a) {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/ * *", buildConfig()); / / 4
return newCorsFilter(source); }} three, the pole body to resolve cross-domain and session@Configuration
public class CorsConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/ * *")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("GET"."POST"."DELETE"."PUT")
.maxAge(3600); }}Copy the code