Spring 响应 ajax: 403 错误

Spring response ajax: 403 error

我正在使用 Spring 和 java-config AbstractAnnotationConfigDispatcherServletInitializer 而不是 web.xml 和我的 spring-controller 代码:

@RequestMapping(value = "/demo1", method = RequestMethod.POST)
public @ResponseBody
String demo1(HttpServletRequest request, HttpServletResponse response) {


    String poreqid = request.getParameter("poid");
    String refid = request.getParameter("refid");
    String status = request.getParameter("key");
    String key = poreqid+ refid+ status;
    return key;
    }
}

当我从 jquery-ajax 发送 post 到 spring 控制器时,jquery 显示错误。 在 jquery 控制台上:

XMLHttpRequest cannot load http://192.168.1.206:8082/project1/demo1. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 403.

我已经添加了

 @ComponentScan
 public class CorsFilter extends OncePerRequestFilter {

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
                                throws ServletException, IOException {

    response.addHeader("Access-Control-Allow-Origin", "*");

    if (request.getHeader("Access-Control-Request-Method") != null &&  "OPTIONS".equals(request.getMethod())) {
        // CORS "pre-flight" request
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
  //            response.addHeader("Access-Control-Allow-Headers", "Content-Type");
  //            response.addHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));
        response.addHeader("Access-Control-Allow-Headers", "X-Requested-With,Content-Type");
        response.addHeader("Access-Control-Max-Age", "1");// 30 min
    }
    filterChain.doFilter(request, response);
  }
}

我没有改变其余代码,请提供解决方案。

您的域 localhost192.168.1.206 被认为是不同的来源,您无法在没有额外设置的情况下从不同的来源发送 ajax 请求。

为了在 Spring MVC 中启用跨源请求,您应该添加一个过滤器,通过在响应中应用适当的 headers 来明确允许请求源,此类过滤器的一个示例

@Component
public class SimpleCORSFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}

}

您可以找到有关该主题的更多阅读材料 here

您可以删除 @Component 并以更传统的方式使用过滤器,方法是在 web.xml

中声明它
<filter>
    <filter-name>cors</filter-name>
    <filter-class>your.package.CorsFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>cors</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>