跨域请求阻止的Spring REST服务+ AJAX

跨域请求阻止的Spring REST服务+ AJAX,第1张

跨域请求阻止的Spring REST服务+ AJAX

我的AJAX通话和服务都还可以。在互联网上搜索了很多之后,我发现它的服务器端问题不是客户端问题。

在Spring的服务器端,我们必须实现允许CORS请求的过滤器

过滤器将如下所示。

import java.io.IOException;import javax.servlet.FilterChain;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.springframework.web.filter.OncePerRequestFilter;public class CORSFilter extends oncePerRequestFilter {    private static final Log LOG = LogFactory.getLog(CORSFilter.class);    @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())) { LOG.trace("Sending Header...."); // CORS "pre-flight" request response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"); // response.addHeader("Access-Control-Allow-Headers", "Authorization"); response.addHeader("Access-Control-Allow-Headers", "Content-Type"); response.addHeader("Access-Control-Max-Age", "1");        }        filterChain.doFilter(request, response);    }}

并在web.xml中将此过滤器应用于您的服务请求,如下所示

    <filter>        <filter-name>cors</filter-name>        <filter-class>com.test.common.controller.CORSFilter</filter-class> <!-- your package name and filter class -->    </filter>    <filter-mapping>        <filter-name>cors</filter-name>        <url-pattern>/*</url-pattern>    </filter-mapping>

这可能会帮助遇到此问题的其他人。:)



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5615164.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存