Spring-BootECMAScript

解决 spring boot 自定义过滤器跨域问题

2018-05-14  本文已影响17人  阿波罗程序猿
使用自定义过滤器的时候

使用自定义过滤器时,采用注解@CrossOrigin会失效,所以用以下代码来搞定

public class TokenFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServlet Requestrequest, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // do something
        cors(request, response);
        // do something
    }
  
    private void cors(HttpServletRequest request, HttpServletResponse response) {
        String allowOrigin = request.getHeader("Origin");
        String allowMethods = "GET,PUT, POST, DELETE";
        String allowHeaders = "Origin,No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified,Cache-Control, Expires, Content-Type, X-E4M-With";
        response.addHeader("Access-Control-Allow-Credentials", "true");
        response.addHeader("Access-Control-Allow-Headers", allowHeaders);
        response.addHeader("Access-Control-Allow-Methods", allowMethods);
        response.addHeader("Access-Control-Allow-Origin", allowOrigin);
    }
}
上一篇下一篇

猜你喜欢

热点阅读