自定义跨域过滤器
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ObjectUtils;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
@Configuration
@Slf4j
public class CorsFilter implements Filter {
private String allowOrigin;
private String allowMethods;
private String allowCredentials;
private String allowHeaders;
private String allowMaxAge;
private String exposeHeaders;
@Override
public void init(FilterConfig filterConfig) {
allowOrigin = "*";
allowMethods = "*";
allowCredentials = "true";
allowHeaders = "accept, content-type, origin, userid, token";
exposeHeaders = "*";
allowMaxAge ="*";
}
/**
* @param req
* @param res
* @param chain
* @throws IOException
* @throws ServletException
* @description 通过CORS技术实现AJAX跨域访问, 只要将CORS响应头写入response对象中即可
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
String clientOrigin = request.getHeader("Origin");
if (clientOrigin != null && !ObjectUtils.isEmpty(allowOrigin)) {
String[] strings = allowOrigin.split(",");
List<String> serverAllowOrigin = Arrays.asList(strings);
if("*".equals(allowOrigin)){
response.setHeader("Access-Control-Allow-Origin", clientOrigin);
}
if (serverAllowOrigin.contains(clientOrigin)) {
response.setHeader("Access-Control-Allow-Origin", clientOrigin);
}
}
if (clientOrigin != null && !ObjectUtils.isEmpty(allowMethods)) {
response.setHeader("Access-Control-Allow-Methods", allowMethods);
}
if (clientOrigin != null && !ObjectUtils.isEmpty(allowCredentials)) {
response.setHeader("Access-Control-Allow-Credentials", allowCredentials);
}
if (clientOrigin != null && !ObjectUtils.isEmpty(allowHeaders)) {
response.setHeader("Access-Control-Allow-Headers", allowHeaders);
}
if (clientOrigin != null && !ObjectUtils.isEmpty(allowMaxAge)) {
response.setHeader("Access-Control-Max-Age", allowMaxAge);
}
if ("OPTIONS".equals(request.getMethod())) {
response.setStatus(200);
return;
}
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
}