美文网首页
利用Filter去解决跨域问题

利用Filter去解决跨域问题

作者: Hugh1029 | 来源:发表于2018-01-26 10:36 被阅读0次

    记录一下,防止遗忘

    第一步:建立一个类,继承自OncePerRequestFilter,代码如下:

    @Component
    public class CORSFilter extends OncePerRequestFilter {
        protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
            httpServletResponse.addHeader("Access-Control-Allow-Origin","*");
            httpServletResponse.addHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE");
            httpServletResponse.addHeader("Access-Control-Allow-Headers","Content-Type");
            httpServletResponse.addHeader("Access-Control-Max-Age","1800");
            filterChain.doFilter(httpServletRequest,httpServletResponse);
        }
    }
    

    第二步:在web.xml中配置过滤器

    <filter>
         <filter-name>cors</filter-name>
         <filter-class>cn.answering.seller.filter.CORSFilter</filter-class>
     </filter>
     <filter-mapping>
         <filter-name>cors</filter-name>
         <url-pattern>/*</url-pattern>
     </filter-mapping>
    

    相关文章

      网友评论

          本文标题:利用Filter去解决跨域问题

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