這幾天在開發中編寫項目時須要先後端分離,恰好涉及到跨域這個問題,很早以前作項目時也用過,也是在網上找的列子,來源已經無處可尋了,若侵必刪!前端
跨域問題通常出現二者服務器不一樣或者不一樣的端口上訪問資源時會存在的問題,本文章目前適用於SpringMVC上,其餘框架暫時還沒涉獵,等之後接觸到後在補充。java
本次解決跨域的問題使用的是 filter.jar 包實現。web
<!--跨域--> <dependency> <groupId>com.thetransactioncompany</groupId> <artifactId>cors-filter</artifactId> <version>2.5</version> </dependency>
(直接複製便可)後端
<!--*****跨域問題*****--> <filter> <filter-name>CORS</filter-name> <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class> <init-param> <param-name>cors.allowOrigin</param-name> <param-value>*</param-value> </init-param> <init-param> <param-name>cors.supportedMethods</param-name> <param-value>GET, POST, HEAD, PUT, DELETE,OPTION</param-value> </init-param> <init-param> <param-name>cors.supportedHeaders</param-name> <param-value>Accept, Origin, X-Requested-With, Content-Type, Last-Modified</param-value> </init-param> <init-param> <param-name>cors.exposedHeaders</param-name> <param-value>Set-Cookie</param-value> </init-param> <init-param> <param-name>cors.supportsCredentials</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>cors.maxAge</param-name> <param-value>3600</param-value> </init-param></filter> <filter-mapping> <filter-name>CORS</filter-name> <url-pattern>/*</url-pattern>
</filter-mapping>
這段配置代碼就不做太多解釋,直接複製便可使用。跨域
import javax.servlet.*; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class KuaY implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Max-Age","3600"); response.setHeader("Access-Control-Allow-Headers","x-requested-with, content-type"); chain.doFilter(req, res); } @Override public void init(FilterConfig filterConfig) {} @Override public void destroy() {} }
以上方式不須要前端編寫任何代碼,直接後臺所有搞定,使用方式就是繼承 KuaY 這個實現類,全部先後端皆可跨域實現。原理能夠本身去研究一下,路漫漫其修遠兮,歡迎拍磚! 服務器