cors解決ajax跨域

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

1、問題描述nginx

A系統和B系統,A系統想經過ajax調用B系統中的後臺方法(B系統SpringMVC)web

2、問題解決ajax

  1.A系統中ajax:spring

                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系統配置  只需配置過濾器json

  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解決,還有一種最簡單的,直接在servlet中寫上一行response.setHeader("Access-Control-Allow-Origin", "*") 就能夠了。app

相關文章
相關標籤/搜索