1. 程式人生 > >java web跨域解決方案

java web跨域解決方案

跨域問題產生的原因是由於在瀏覽器的訪問域名為A網站時,A網站的頁面訪問B域名的網路請求時,使用A的域名請求B的業務兩個請求為服務不在同一域名下從而產生的問題。(通常在Ifream,ajax請求外網伺服器產生該問題出現)

具體解決機制為:

B域名下服務允許A域名下的網頁內部請求B的服務

解決方案為

一、註解方式

       推薦這種方法,簡單快捷,但Spring版本需要4.2以上,只需在spring-context.xml檔案中新增如下配置即可,然後初始化時掃描這個檔案<!-- 解決跨域請求問題,spring版本需4.2以上 -->

<mvc:cors>
    <mvc:mapping path="/**/**"
                 allowed-origins="*"
                 allowed-methods="POST, GET, OPTIONS, DELETE, PUT"
                 allowed-headers="Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"
                 allow-credentials="true" />
</mvc:cors>

<servlet>
   <servlet-name>mvc-dispatcher</servlet-name>
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
   <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>
         classpath:config/spring-*.xml
      </param-value>
   </init-param>
       <load-on-startup>1</load-on-startup>
</servlet>

例:No 'Access-Control-Allow-Origin' header is present on the requested resource.'Ajax跨域訪問解決方案問題

由於請求頭部沒有允許頭為Access-Control-Allow-Origin的標籤的請求,異常不出跨域問題

解決機制為,在允許的頭設定裡面新增Access-Control-Allow-Origin
二、攔截器方式

        這種方法需要實現 Filter的doFilter方法,如下,即在web.xml檔案中新增過濾器的配置,其中“ssm.util.filter.CORSFilter”是CORSFilter的引用位置

public class CORSFilter implements Filter {

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

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
     HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.addHeader("Access-Control-Allow-Origin", "*");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    public void destroy() {}
}

<!--解決跨域訪問-->

<filter>
   <filter-name>CORSFilter</filter-name>
   <filter-class>ssm.util.filter.CORSFilter</filter-class>
</filter>
<filter-mapping>
   <filter-name>CORSFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>


---------------------
作者:lankezhou
來源:CSDN
原文:https://blog.csdn.net/lankezhou/article/details/72491019?utm_source=copy
版權宣告:本文為博主原創文章,轉載請附上博文連結!