zoukankan      html  css  js  c++  java
  • 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>
        <!-- 跨域拦截器 -->
  • 相关阅读:
    Springboot启动前执行方法
    UUID
    vue
    前端进阶
    动态代理
    c# 对接微信公众号JSSDK使用wx.uploadImage 上传图片,后台从微信服务器上下载的图片有问题损坏的解决办法
    浏览器数据库 IndexedDB基础使用
    使用Java命令行编译和打包jar
    ArcGIS JS API 路径回放
    基于Quick_SLPK_Server的NodeJs版I3S服务发布
  • 原文地址:https://www.cnblogs.com/zhou-pan/p/9274490.html
Copyright © 2011-2022 走看看