用springboot 搭建一套簡易的前後端程式碼
阿新 • • 發佈:2019-02-01
(1)先把spring 基礎專案創建出來。參考文章(點選以下連結):
(2)前後端分離,為解決跨域問題,寫一個過濾器設定header。注意,springboot 增加過濾器需要在啟動類增加註解
@ServletComponentScan
@WebFilter(filterName = "accessFilter",urlPatterns = "/*") public class AccessFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { //用過濾器這樣設定header可以解決跨域問題 HttpServletResponse response = (HttpServletResponse) servletResponse; response.setHeader("Access-Control-Allow-Origin", "*"); filterChain.doFilter(servletRequest,servletResponse); } }
(3)現在開始寫後端。
@Controller public class HellowordController { @GetMapping(path = "/testJson") @ResponseBody public User testJson(){ //User是一個普通的Bean,有屬性id和name,不貼出來了 //注意加上@ResponseBody 才可以返回json到前端 User userInfo = new User() ; userInfo.setId(Long.getLong("123")); userInfo.setName("zhihao"); return userInfo; } }
(4)在前端用js傳送ajax請求到後端。需要新增jQuery。
$(function(){ var url = 'http://localhost:8080/testJson'; $.ajax({ url:url, type:"get", //dataType:"json", data:{ userID:"1" }, success:function(response){ console.log('success back........') console.log(response) console.log("屬性") console.log(response.name) }, error:function(response) { console.log('error back........') console.log(response) } }); });
(5)在瀏覽器用F12開啟除錯面板,點選console介面。檢視測試結果,成功!