美文网首页
Spring Boot 12 -- 添加过滤器解决跨域问题

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

作者: 半碗鱼汤 | 来源:发表于2019-08-23 21:25 被阅读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 详解

相关文章

网友评论

      本文标题:Spring Boot 12 -- 添加过滤器解决跨域问题

      本文链接:https://www.haomeiwen.com/subject/ukjxectx.html