SpringBoot系列---【统一解决跨域】

注意: CorFilter / WebMvConfigurer / @CrossOrigin 需要 SpringMVC 4.2以上版本才支持,对应springBoot 1.3版本以上。

1.重写WebMvcConfigurer(全局跨域)

import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
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("/**").
                //允许跨域的域名,可以用*表示允许任何域名使用
                allowedOrigins("*").
                //允许任何方法(post、get等)
                allowedMethods("*").
                //允许任何请求头
                allowedHeaders("*").
                //带上cookie信息
                allowCredentials(true).
                //maxAge(3600)表明在3600秒内,不需要再发送预检验请求,可以缓存该结果
                exposedHeaders(HttpHeaders.SET_COOKIE).maxAge(3600L);
    }
}

2.通过实现Fiter接口在请求中添加一些Header来解决跨域的问题

@Component
public class CorsFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletResponse res = (HttpServletResponse) response;
        res.addHeader("Access-Control-Allow-Credentials", "true");
        res.addHeader("Access-Control-Allow-Origin", "*");
        res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
        res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN");
        if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) {
            response.getWriter().println("ok");
            return;
        }
        chain.doFilter(request, response);
    }
    @Override
    public void destroy() {
    }
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
}

3.使用注解 @CrossOrigin,加在contrlller类上

posted on 2022-01-28 22:26  少年攻城狮  阅读(170)  评论(0)    收藏  举报

导航