java SSM 解決跨域問題


什么是跨域

跨域是指從一個域名的網頁去請求另一個域名的資源。比如從www.baidu.com 頁面去請求 www.google.com 的資源。跨域的嚴格一點的定義是:只要 協議,域名,端口有任何一個的不同,就被當作是跨域

前段時間接觸一個新的項目,原本想着做成前后端分離的,但是這樣就會涉及到 ajax 跨域的問題,那時候沒解決,所以就沒搞前后端分離,但是今天的項目又接觸到跨域(前后端分離的問題),研究了一晚上,查了很多資料,也跟一些前輩溝通過,用的方法都不同,

有人說用谷歌的插件,有人說用Nginx 做個反向代理,更有人說,用 JSONP 的方式,這這些個方法都可行,可是操作難度有點大啊,第一個先不說,要翻牆出去才能下載安裝,第二個,對於很多新手來說,更是難以理解,

第三個, JSONP 只能是使用 get 方式請求數據,可是我們用 get 方式去請求數據的,這都是少數情況吧?所以,我綜合了一下,希望能幫到更多的小伙伴!

這個配置允許跨域完全是在我們 后台的事,跟前端無關,我所用的后端框架是 SSM (其實也就是 Spring 的問題),其他框架的,請繞道!!!!(有接觸 Nutz 框架的,這個框架的跨域更加簡單,加一個注解就行了:@Filters(@By(type=CrossOriginFilter.class))

好了,廢話多了,言歸正傳,其實就 三部曲 就可以了,

 

1. 新建一個過濾器,並實現 Filter 接口

請注意導包!!!!

public class SimpleCORSFilter implements Filter {
    private boolean isCross = false;

    @Override
    public void destroy() {
        isCross = false;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        if (isCross) {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            System.out.println("攔截請求: " + httpServletRequest.getServletPath());
            httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
            httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            httpServletResponse.setHeader("Access-Control-Max-Age", "0");
            httpServletResponse.setHeader("Access-Control-Allow-Headers",
                    "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token");
            httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
            httpServletResponse.setHeader("XDomainRequestAllowed", "1");
        }
        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String isCrossStr = filterConfig.getInitParameter("IsCross");
        isCross = isCrossStr.equals("true") ? true : false;
        System.out.println(isCrossStr);
    }

}

 

2. 在web.xml中設配置

 

 <!-- 跨域請求 -->  
     <filter>  
       <filter-name>SimpleCORSFilter</filter-name>  
       <filter-class>com.ssm.util.SimpleCORSFilter</filter-class>  
       <init-param>  
           <param-name>IsCross</param-name>  
           <param-value>true</param-value>  
       </init-param>  
   </filter>  
   <filter-mapping>  
       <filter-name>SimpleCORSFilter</filter-name>  
       <url-pattern>/*</url-pattern>  
   </filter-mapping>  

 

 

 

 

3. 在 StringMVC 的配置文件中配置跨域請求

 

      <!-- 接口跨域配置 -->  
      <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>  

 

Spring MVC 的跨域配置,到此結束,前端不用改任何東西,正常的使用 ajax 即可

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM