利用Filter去解决跨域问题

2018-01-26  本文已影响0人  Hugh1029

记录一下,防止遗忘

第一步:建立一个类,继承自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>
上一篇下一篇

猜你喜欢

热点阅读