基础框架中默认提供ApiCorsFilter跨域处理Filter,默认情况下关闭.

默认实现

  1. public class ApiCorsFilter implements Filter {
  2. @Override
  3. public void init(FilterConfig filterConfig) throws ServletException {
  4. }
  5. @Override
  6. public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
  7. HttpServletResponse res = (HttpServletResponse) servletResponse;
  8. res.addHeader("Access-Control-Allow-Credentials", "true");
  9. res.addHeader("Access-Control-Allow-Origin", "*");
  10. res.addHeader("Access-Control-Allow-Methods", "POST,GET,PUT,OPTIONS,DELETE");
  11. res.addHeader("Access-Control-Allow-Headers", "*");
  12. res.setHeader("Content-Type", "application/json;charset=UTF-8");
  13. if ("OPTIONS".equals(((HttpServletRequest) servletRequest).getMethod())) {
  14. servletResponse.getWriter().println("ok");
  15. return;
  16. }
  17. filterChain.doFilter(servletRequest, servletResponse);
  18. }
  19. @Override
  20. public void destroy() {
  21. }
  22. }

开关配置

  1. xy.core.api.cors.enable=true

注意事项

当web前端直接调用后方服务时,可能会产生跨域,此时开启跨域功能即可。

对于从网关转发而来的请求,默认网关做了跨域处理,因此当前应用中无需再此开启跨域功能。