1. 程式人生 > >CORS跨域請求:前後端分離

CORS跨域請求:前後端分離

跨域

  • 請求過濾器:

    /**
    *  OncePerRequestFilter保證在任何Servlet容器中都是一個請求只執行一次的過濾器。
    */
    public class CorsFilter extends OncePerRequestFilter {
    
    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse resp, FilterChain chain) throws ServletException, IOException {
    
        Properties props = PropertiesLoaderUtils.loadAllProperties("cors.properties");
        //允許的 客戶端域名
        resp.addHeader("Access-Control-Allow-Origin", props.getProperty("cors.allowed-origins"));
        //允許的 方法名
        resp.addHeader("Access-Control-Allow-Methods", props.getProperty("cors.allowed-methods"));
        //允許服務端訪問的客戶端請求頭,多個請求頭用逗號分割,例如:Content-Type
        resp.addHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With,token");
        //預檢驗請求時間
        resp.addHeader("Access-Control-Max-Age", props.getProperty("cors.max-age"));//30 min
        resp.addHeader("Access-Control-Allow-Credentials", "true");
    
        chain.doFilter(req, resp);
    }
    }

    技術分享圖片

  • web.xml中配置跨域過濾器:
    <!--配置跨域請求的過濾器-->
    <filter>
    <filter-name>cors</filter-name>
    <filter-class>com.jd.dashboard.cors.CrossFilter</filter-class>
    </filter>
    <filter-mapping>
    <filter-name>cors</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping>

  • 過濾器中的屬性配置如下:
  • #跨域請求CORS全局配置屬性值
    
    #允許訪問的客戶端域名,例如:http://web.xxx.com
    cors.allowed-origins=http://front.xx.com
    
    #允許訪問的方法名
    cors.allowed-methods=POST, GET, OPTIONS, DELETE
    
    #允許服務端訪問的客戶端請求頭,多個請求頭用逗號分割,例如:Content-Type
    cors.allowed-headers=Content-Type
    
    #允許客戶端訪問的服務端響應頭
    cors.exposed-headers=
    
    #是否允許請求帶有驗證信息,若要獲取客戶端域下的cookie時,需要將其設置為true
    cors.allow-credentials=true
    
    cors.max-age=1800
    

    由於jsonp只支持GET方式的請求,所以這種方式比較推薦。

    CORS跨域請求:前後端分離