SpringBoot 三步骤轻松解决跨域

来源:互联网 发布:万能网络摄像机客户端 编辑:程序博客网 时间:2024/06/07 03:29

1、添加maven依赖注解

       <!--跨域需要的jar包-->        <dependency>            <groupId>com.thetransactioncompany</groupId>            <artifactId>java-property-utils</artifactId>            <version>1.9.1</version>        </dependency>        <dependency>            <groupId>com.thetransactioncompany</groupId>            <artifactId>cors-filter</artifactId>            <version>2.5</version>        </dependency>        <dependency>            <groupId>javax.servlet</groupId>            <artifactId>javax.servlet-api</artifactId>            <version>3.1.0</version>            <scope>provided</scope>        </dependency>

2、添加跨域请求配置类CorsConfig

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;@Configurationpublic 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);    }}

3、在接收到OPTIONS请求时候,需要返回状态码为202,并且设置响应头部(根据需求变更)

HttpServletResponse httpResponse = response;        httpResponse.setCharacterEncoding("UTF-8");        httpResponse.setContentType("application/json; charset=utf-8");        httpResponse.setHeader("Access-Control-Allow-Origin","*");        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");        httpResponse.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE,PATCH,PUT");        httpResponse.setHeader("Access-Control-Max-Age", "3600");        httpResponse.setHeader("Access-Control-Allow-Headers", "Origin,X-Requested-With,x-requested-with,X-Custom-Header," +                "Content-Type,Accept,Authorization");        String method = request.getMethod();        if ("OPTIONS".equalsIgnoreCase(method)){            logger.info("OPTIONS请求");            httpResponse.setStatus(HttpServletResponse.SC_ACCEPTED);        }