先後端分離開發中,跨域問題是很常見的一種問題。本文主要是解決 springboot
項目跨域訪問的一種方法,其餘 javaweb
項目也可參考。javascript
因爲先後端分離開發中前端頁面與後臺在不一樣的服務器上,一定會出現跨區問題。關於更具體的信息,能夠看這裏:不要再問我跨域的問題了html
前端代碼:前端
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script type="text/javascript" src="js/vendor/jquery-1.10.2.min.js"></script> <script type="text/javascript"> $(function(){ $("a").click(function(){ var url = 'http://127.0.0.1:8080/example/testget'; var args = {"time" : new Date()}; //get請求 $.get(url, args, function(data){ alert(data); }); //禁止頁面跳轉 return false; }); }); </script> </head> <body> <h1>Test</h1> <li><a href="">click</a></li> </body> </html>
出現了跨域問題:java
後端代碼:jquery
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.Map; @RestController @RequestMapping(value = "/example") public class CrosTestController { @GetMapping(value = "/testget") public Map<String, String> testGet(){ Map<String, String> testMap = new HashMap<>(); testMap.put("name", "jack"); //用來打印驗證後端代碼確實執行了,即該接口確實被訪問了 System.out.println("執行了!"); return testMap; } }
無需改動前端代碼,在 springboot
項目中添加全局過濾器:web
import com.example.filter.CrosFilter; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; @SpringBootApplication public class exampleApplication { public static void main(String[] args) { SpringApplication.run(exampleApplication.class, args); } /** * 配置跨域訪問的過濾器 * @return */ @Bean public FilterRegistrationBean registerFilter(){ FilterRegistrationBean bean = new FilterRegistrationBean(); bean.addUrlPatterns("/*"); bean.setFilter(new CrosFilter()); return bean; } }
過濾器:ajax
import javax.servlet.*; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class CrosFilter implements javax.servlet.Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletResponse res = (HttpServletResponse) servletResponse; //*號表示對全部請求都容許跨域訪問 res.addHeader("Access-Control-Allow-Origin", "*"); res.addHeader("Access-Control-Allow-Methods", "*"); filterChain.doFilter(servletRequest, servletResponse); } @Override public void destroy() { } }
再看前端訪問結果,已經能夠正常訪問了:spring