Spring MVC的跨網域設定

來源:互聯網
上載者:User
近期項目用到跨域訪問,正常情況下使用`response.setHeader("Access-Control-Allow-Origin", "*")`在回應標頭部添加了允許跨域的頭部後即可接受簡單請求(GET、POST等)的訪問。但是一旦在請求的header中增加其他參數,瀏覽器在跨域訪問資源前就會使用OPTIONS請求嘗試擷取握手資訊,上述方法便無法通過過濾器的篩選,導致404出現。故,請教同事,使用apache提供的Corsfilter全域解決跨域問題。具體內容如下:引入依賴
<dependency>    <groupId>org.apache.tomcat</groupId>    <artifactId>tomcat-catalina</artifactId>    <version>8.0.15</version>    <scope>provided</scope><!--這裡配置是在打包時忽略該組件--></dependency>
在web.xml中添加CorsFilter過濾器:
<filter>    <filter-name>corsFilter</filter-name>    <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>    <init-param>        <param-name>cors.allowed.origins</param-name>        <!--對所有合格資源生效-->        <param-value>*</param-value>    </init-param>    <init-param>        <param-name>cors.allowed.methods</param-name>        <!--允許GET、POST請求-->        <param-value>GET,POST</param-value>    </init-param>    <init-param>        <param-name>cors.allowed.headers</param-name>        <!--配置所有請求header中需要添加的資訊,超出該範圍,會被阻止訪問-->        <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,token,userCode</param-value>    </init-param>    <init-param>        <param-name>cors.support.credentials</param-name>        <!--不允許使用cookie-->        <param-value>false</param-value>    </init-param>    <init-param>        <param-name>cors.support.maxage</param-name>        <!--一次握手資訊後,2700ms內不用再次認證-->        <param-value>2700</param-value>    </init-param></filter><filter-mapping>    <filter-name>characterEncodingFilter</filter-name>    <!--這裡允許所有資源的跨域,可視具體情況調整-->    <url-pattern>/*</url-pattern></filter-mapping>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.