美文网首页
springboot通过Filter开启跨域

springboot通过Filter开启跨域

作者: c_8f5b | 来源:发表于2019-01-31 14:54 被阅读0次
    首先需要自定义一个过滤器实现Filter接口

    public class HeaderFilter implements Filter

    然后重写doFilter方法
        @Override
        public void doFilter(ServletRequest request, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
            HttpServletResponse response = (HttpServletResponse) resp;
            //解决跨域访问报错
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
            //设置过期时间
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, client_id, uuid, Authorization");
            // 支持HTTP 1.1.
            response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
            // 支持HTTP 1.0. response.setHeader("Expires", "0");
            response.setHeader("Pragma", "no-cache");
            // 编码
            response.setCharacterEncoding("UTF-8");
            chain.doFilter(request, resp);
        }
    
    最后在类上加@Component注解,声明其是一个组件,再加上@WebFilter(urlPatterns = { "需要过滤的url" }, filterName = "过滤器的名称")
    完整代码
    @Slf4j
    @Component
    @WebFilter(urlPatterns = { "/api/*" }, filterName = "headerFilter")
    public class HeaderFilter implements Filter {
        @Override
        public void doFilter(ServletRequest request, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
            HttpServletResponse response = (HttpServletResponse) resp;
            //解决跨域访问报错
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
            //设置过期时间
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, client_id, uuid, Authorization");
            // 支持HTTP 1.1.
            response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
            // 支持HTTP 1.0. response.setHeader("Expires", "0");
            response.setHeader("Pragma", "no-cache");
            // 编码
            response.setCharacterEncoding("UTF-8");
            chain.doFilter(request, resp);
        }
    
        @Override
        public void init(FilterConfig filterConfig) {
            log.info("跨域过滤器启动");
        }
    
        @Override
        public void destroy() {
            log.info("跨域过滤器销毁");
        }
    }
    

    相关文章

      网友评论

          本文标题:springboot通过Filter开启跨域

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