@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest servletRequest = (HttpServletRequest) request; HttpServletResponse servletResponse = (HttpServletResponse) response; String origin = "*"; if (!StringUtil.isEmpty(servletRequest.getHeader("Origin"))) { origin = servletRequest.getHeader("Origin"); } servletResponse.addHeader("Access-Control-Allow-Origin", origin); servletResponse.addHeader("Access-Control-Allow-Credentials", "true"); if (servletRequest.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(servletRequest.getMethod())) { // CORS "pre-flight" request servletResponse.addHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS"); servletResponse.addHeader("Access-Control-Allow-Headers", "X-Requested-With,Origin,Content-Type, Accept,access_token,Cache-Control,X-Requested-With,x-access-token"); servletResponse.setStatus(HttpStatus.OK.value()); return; } chain.doFilter(request, response); } 或者
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest servletRequest = (HttpServletRequest) request; HttpServletResponse servletResponse = (HttpServletResponse) response; String origin = "*"; if (!StringUtil.isEmpty(servletRequest.getHeader("Origin"))) { origin = servletRequest.getHeader("Origin"); } servletResponse.addHeader("Access-Control-Allow-Origin", origin); servletResponse.addHeader("Access-Control-Allow-Credentials", "true"); servletResponse.addHeader("Access-Control-Allow-Headers", "X-Requested-With,Origin,Content-Type, Accept,access_token,Cache-Control,X-Requested-With,x-access-token"); chain.doFilter(request, response); }