基础框架中默认提供ApiCorsFilter跨域处理Filter,默认情况下关闭.
默认实现
public class ApiCorsFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) servletResponse;
res.addHeader("Access-Control-Allow-Credentials", "true");
res.addHeader("Access-Control-Allow-Origin", "*");
res.addHeader("Access-Control-Allow-Methods", "POST,GET,PUT,OPTIONS,DELETE");
res.addHeader("Access-Control-Allow-Headers", "*");
res.setHeader("Content-Type", "application/json;charset=UTF-8");
if ("OPTIONS".equals(((HttpServletRequest) servletRequest).getMethod())) {
servletResponse.getWriter().println("ok");
return;
}
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
开关配置
xy.core.api.cors.enable=true
注意事项
当web前端直接调用后方服务时,可能会产生跨域,此时开启跨域功能即可。
对于从网关转发而来的请求,默认网关做了跨域处理,因此当前应用中无需再此开启跨域功能。