Ajax跨域后台处理

Posted zhoupan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Ajax跨域后台处理相关的知识,希望对你有一定的参考价值。

页面报错: Failed to load http://localhost:8080/websites/webInterface/queryNewsList: Response to preflight request doesn‘t pass access control check: No ‘Access-Control-Allow-Origin‘ header is present on the requested resource. Origin ‘http://127.0.0.1:8020‘ is therefore not allowed access.


package com.xxx.websites.commons.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.httpclient.HttpStatus; /** * * @ClassName:CorsFilter * @Description:TODO(统一处理跨域请求) * @author: xxx * @date 2018年7月4日 上午11:11:19 * * @Copyright: 2018 www.zsplat.com Inc. All rights reserved. */ public class CorsFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse _response = (HttpServletResponse) response; HttpServletRequest _request = (HttpServletRequest) request; // 指定允许其他域名访问 _response.setHeader("Access-Control-Allow-Origin", "*"); // 响应类型 _response.setHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, OPTIONS, DELETE"); // 响应头设置 _response.setHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with, X-Custom-Header, HaiYi-Access-Token"); if ("OPTIONS".equals(_request.getMethod())){ _response.setStatus(HttpStatus.SC_NO_CONTENT); } chain.doFilter(request, response); } @Override public void destroy() { } }

web.xml中配置 

<!-- 跨域拦截器 -->
    <filter>
        <filter-name>cors</filter-name>
        <filter-class>com.zsplat.websites.commons.filter.CorsFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>cors</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- 跨域拦截器 -->

 




以上是关于Ajax跨域后台处理的主要内容,如果未能解决你的问题,请参考以下文章

ajax跨域请求的处理

如何解决ajax跨域问题

关于跨域的处理的几种方法的整理

AJAX四种跨域处理方法

ajax跨域请求解决方案

Ajax 跨域问题及其解决方案