Spring Boot 12 -- 添加过滤器解决跨域问题

2019-08-23  本文已影响0人  半碗鱼汤

一、解决跨域

在控制器上或者接口方法上加注解 @CrossOrigin(origins = "*", allowCredentials = "true", maxAge = 3600)

@CrossOrigin(origins = "*", allowCredentials = "true", maxAge = 3600)

二、补充

如果上面的方法还不可以,那么再加一个过滤器

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = "/*", filterName = "CorsFilter")
public class CorsFilter 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-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        response.setHeader("Access-Control-Expose-Headers", "Location");
        chain.doFilter(req, res);
    }

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void destroy() {
    }

}

再在启动类加一个注解扫描到这个过滤器类 @ServletComponentScan

@ServletComponentScan

三、其他资料

跨域资源共享 CORS 详解

上一篇下一篇

猜你喜欢

热点阅读