码迷,mamicode.com
首页 > Web开发 > 详细

Ajax跨域后台处理

时间:2018-07-06 17:43:34      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:XML   row   指定   pat   xxx   att   servlet   present   cors   

页面报错: 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跨域后台处理

标签:XML   row   指定   pat   xxx   att   servlet   present   cors   

原文地址:https://www.cnblogs.com/zhou-pan/p/9274490.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!