//第一种方式,博客侧边栏公告

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>
    <!-- 跨域拦截器 -->

 

posted @ 2018-07-06 16:51  zhoupan  阅读(150)  评论(0编辑  收藏  举报