springboot使用Filter解決前後端分離,產生的跨域問題

Merci_Sen發表於2018-06-22

環境:IDEA編寫後端程式碼,前端使用HBuilder實現。

問題描述:Failed to load http://localhost:8080/user/login: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8020' is therefore not allowed access. 

問題產生:Ajax請求路徑為 http://localhost:8080/user/login

可以檢視瀏覽器中詳細資訊

    

因為瀏覽器的同源策略,所謂的同源是指,域名,協議,埠相同

因此產生了跨域問題,解決方式如下:

1.在自己的專案下建立一個類,我這裡是PassHttpFilter類

    

2.具體程式碼:

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
@WebFilter(urlPatterns = "/*", filterName = "authFilter")  //這裡的“/*” 表示的是需要攔截的請求路徑
public class PassHttpFilter implements Filter {

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

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse httpResponse = (HttpServletResponse)servletResponse;
        httpResponse.setHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept");
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpResponse.addHeader("Access-Control-Allow-Origin", "http://127.0.0.1:8020");
        filterChain.doFilter(servletRequest, httpResponse);
    }

    @Override
    public void destroy() {
    }
}
@WebFilter(urlPatterns = "/*", filterName = "authFilter"

    /* 是允許攔截請求的url,表示所有的請求

    authFilter 是攔截器的名稱

3.在doFilter方法中新增如下程式碼

  HttpServletResponse httpResponse = (HttpServletResponse)servletResponse;
  httpResponse.setHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept");
  httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
  httpResponse.addHeader("Access-Control-Allow-Origin", "http://127.0.0.1:8020");
說明:httpResponse.addHeader("Access-Control-Allow-Origin","http://127.0.0.1:8020")新增的響應的地址;

4.這樣就行了,啟動專案可以在視窗看到對應的Filter的啟動資訊 ,這樣就解決了跨域問題,輕鬆做到前後端分離。

    2018-06-22 14:46:29.965  INFO 19188 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'passHttpFilter' to: [/*]


相關文章