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; /** * Created by myz on 2017/7/10. * * 设置跨域请求 */ @Configuration public class CorsConfig { private CorsConfiguration buildConfig() { CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedOrigin("*"); // 1 设置访问源地址 corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头 corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法 return corsConfiguration; } @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", buildConfig()); // 4 对接口配置跨域设置 return new CorsFilter(source); } }
第二种配置方法
import 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.HttpServletResponse; import org.springframework.stereotype.Component; /** * Created by myz on 2017/7/10. * * 设置跨域请求 */ @Component public class CorsConfig implements Filter{ @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response=(HttpServletResponse)res; response.setHeader("Access-control-Allow-Origin", "*"); response.setHeader("Access-control-Allow-Credentials", "true"); response.setHeader("Access-control-Allow-Methods", "*"); response.setHeader("Access-control-Max-Age", "3600"); response.setHeader("Access-control-Allow-Headers", "Content-Type,Access-Token"); } @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void destroy() { } }