記錄初學springboot踩的一點坑
首先我登錄頁面直接通過瀏覽器請求直接訪問的,項目結構如圖所示
- 登錄頁面
1 <form action="index" id="frm"> 2 <input type="text" name="dname"> 3 <input type="text" name="loc"> 4 <input type="button" value="提交" id="but" ></form> 5 <script src="js/jquery-1.12.2.js"></script> 6 <script> 7 $(function () { 8 $("#but").click(function(){ 9 var data = $("#frm").serialize(); 10 $.get("index",data); 11 }) 12 }) 13 </script>
點擊提交后,是一個ajax發送表單里面的數據,請求地址為index,會去數據庫里面查詢是否有這個人(后端采用mybatis去數據庫查詢),根據返回的結果,跳到相應的頁面去,我在controller里面寫的index請求的java代碼為:
1 // 登錄 2 @GetMapping("index") 3 public String addDept(Dept dept) { 4 log.info("dept===" + dept); 5 List<Dept> depts = deptService.selectDept(dept); 6 if (depts != null) { 7 return "index"; 8 } else { 9 return "error"; 10 } 11 }
意外的事情出現了,有查詢結果出來,而且也進入了if判斷,但就是沒有跳轉頁面,這個問題困惑了許久,一直沒想到問題出現在哪里,百度了很多,其中百度給的結果有以下幾點:
- 注解使用@Controller 而不是@RestController,因為使用@RestController會返回“index”字符串
- 首先在pom文件中引入模板引擎jar包,即:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency> - 在application.properties中配置模板引擎
spring.thymeleaf.prefix=classpath:/templates/
- 不加@responseBody注解,因為加了之后會返回一個字符串的形式;
以上的這些坑,我都試了,最后還是沒有失敗,但是我直接在瀏覽器上輸入index請求,會跳轉到index.html的頁面上面去,我就很納悶了,還是不知道我的問題出現在哪里
我的index.html的頁面如下,用ajax請求,調用去數據庫查詢所有人的請求,代碼如下:
1 index頁面 2 <script src="../js/jquery-1.12.2.js"></script> 3 <script> 4 selectDept() 5 function selectDept() { 6 $.get("getDept",callSelectDept,"JSON") 7 function callSelectDept(data) { 8 var str="" 9 for (var i =0;i<data.length;i++){ 10 str+=data[i].deptno+"---"+data[i].dname+"---"+data[i].loc+ 11 "<a href=deleteDept?deptno='"+data[i].deptno+"'>刪除</a>"+ 12 "<a href=updateDept?deptno='"+data[i].deptno+"'>修改</a>" 13 +"<br/>" 14 } 15 $("#queryDept").append(str) 16 } 17 }
當通過瀏覽器訪問index.html后,會顯示出來數據,這里是沒有問題的
后來過了一段時間吧,才想起來是不是ajax請求調用方法后,在java后端發送跳轉頁面請求后,不能跳轉頁面,因為ajax默認是異步請求嘛.代碼如下
1 $.ajax({ 2 asyn:false, 3 url:"index", 4 type:"get", 5 data:data 6 })
后來將ajax請求改為同步之后,還是失敗,最后,將提交表單的方式改為summit,成功!!!
1 <form action="index" id="frm"> 2 <input type="text" name="dname"> 3 <input type="text" name="loc"> 4 <input type="submit" value="提交" ></form>
總結:ajax請求最好只用於發送數據,和從后端拿數據,不要做跳轉頁面的...如果一定要做頁面的跳轉,可以約定后端放回的數據為1或0,當返回的數據為1時,用Windows.location.href="index.html"來跳轉
具體代碼如下:
1 function callback(dat){ 2 if (dat=1){ 3 window.location.href="index.html" 4 }else { 5 alert("1") 6 }
否則就用submit提交,記住了,ajax用於發送請求到那個方法后,后端是跳轉不了頁面的,也不會報錯,因為ajax用於默認是異步請求,如果要跳就在前端跳轉頁面也是可以的
這個坑記錄下來,為后來的你們給與一些建議!!!