spring mvc spring boot 允许跨域请求 配置类

2019-05-25 18:07:11 浏览数 (1)

用@Component 注释下,随便放个地方就可以了

代码语言:javascript复制
package com.chinaws.wsarchivesserver.core.config;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CorsFilter implements Filter {
  
    final static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(CorsFilter.class);  
  
    /*跨域请求配置*/
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
  
        HttpServletRequest reqs = (HttpServletRequest) req;
  
        response.setHeader("Access-Control-Allow-Origin",reqs.getHeader("Origin"));  
        response.setHeader("Access-Control-Allow-Credentials", "true");  
        response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "5000");  
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With,X-XSRF-TOKEN,x-token");
        chain.doFilter(req, res);  
    }  
    public void init(FilterConfig filterConfig) {}
    public void destroy() {}  
}

0 人点赞