cors解决ajax跨域

时间:2023-02-25 14:18:07

此方法只支持spring4.2及以上版本

一、问题描述

A系统和B系统,A系统想通过ajax调用B系统中的后台方法(B系统SpringMVC)

二、问题解决

  1.A系统中ajax:

                var str = "{'id':'89','fundCode':'000311'}";    
                jQuery.ajax({
                    url:'http://172.88.88.888:8180/test/app/product/public/getManaAndComp',
                    type:"post",
                    dataType:"text",
                    data:{"param":str,"osFlag":'3'},
                    async:true,
                    success:function(serverinfo){
                        console.log(serverinfo);
                        var Data=Base64.decode(serverinfo);                            
                        Data=JSON.parse(Data);
                        console.log(Data);
                    }, // success 结束
                    error:function(){
                        console.log('error');                
                    }
                });

 

  2.B系统配置  只需配置过滤器

  web.xml

     <filter>
        <filter-name>cors</filter-name>
        <filter-class>com.datangwealth.common.filter.CorsConfig</filter-class>
     </filter>
     <filter-mapping>
        <filter-name>cors</filter-name>
        <url-pattern>/*</url-pattern>
     </filter-mapping>

CorsConfig.java
package com.datangwealth.modules.monitor.service;

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.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;



public class CorsConfig  implements Filter {

    @Override
    public void destroy() {
     
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
            FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        response.setHeader("Access-Control-Allow-Origin", "*");           
        String token = request.getHeader("token");
        System.out.println("filter origin:"+token);//通过打印,可以看到一次非简单请求,会被过滤两次,即请求两次,第一次请求确认是否符合跨域要求(预检),这一次是不带headers的自定义信息,第二次请求会携带自定义信息。
        if ("OPTIONS".equals(request.getMethod())){//这里通过判断请求的方法,判断此次是否是预检请求,如果是,立即返回一个204状态吗,标示,允许跨域;预检后,正式请求,这个方法参数就是我们设置的post了
          response.setStatus(204); //HttpStatus.SC_NO_CONTENT = 204
          response.setHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, OPTIONS, DELETE");//当判定为预检请求后,设定允许请求的方法
          response.setHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with, Token"); //当判定为预检请求后,设定允许请求的头部类型
          response.addHeader("Access-Control-Max-Age", "3600");                           
        }
        filterChain.doFilter(servletRequest, servletResponse); 
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        
    } 
}

 

这样就解决了跨域的问题,跨域还可以使用jsonp、配置nginx解决。