這篇文章主要介紹了springboot無法跳轉頁面的問題解決方案,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
首先我登錄頁面直接通過瀏覽器請求直接訪問的,項目結構如圖所示
登錄頁面
<form action="index" id="frm"> <input type="text" name="dname"> <input type="text" name="loc"> <input type="button" value="提交" id="but" ></form> <script src="js/jquery-1.12.2.js"></script> <script> $(function () { $("#but").click(function(){ var data = $("#frm").serialize(); $.get("index",data); }) }) </script>
點擊提交後,是一個ajax發送表單裏面的數據,請求地址爲index,會去數據庫裏面查詢是否有這個人(後端採用mybatis去數據庫查詢),根據返回的結果,跳到相應的頁面去,我在controller裏面寫的index請求的java代碼爲:
// 登錄 @GetMapping("index") public String addDept(Dept dept) { log.info("dept===" + dept); List<Dept> depts = deptService.selectDept(dept); if (depts != null) { return "index"; } else { return "error"; } }
意外的事情出現了,有查詢結果出來,而且也進入了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請求,調用去數據庫查詢所有人的請求,代碼如下:
index頁面 <script src="../js/jquery-1.12.2.js"></script> <script> selectDept() function selectDept() { $.get("getDept",callSelectDept,"JSON") function callSelectDept(data) { var str="" for (var i =0;i<data.length;i++){ str+=data[i].deptno+"---"+data[i].dname+"---"+data[i].loc+ "<a href=deleteDept?deptno='"+data[i].deptno+"'>刪除</a>"+ "<a href=updateDept?deptno='"+data[i].deptno+"'>修改</a>" +"<br/>" } $("#queryDept").append(str) } }
當通過瀏覽器訪問index.html後,會顯示出來數據,這裏是沒有問題的
後來過了一段時間吧,纔想起來是不是ajax請求調用方法後,在java後端發送跳轉頁面請求後,不能跳轉頁面,因爲ajax默認是異步請求嘛.代碼如下
$.ajax({ asyn:false, url:"index", type:"get", data:data })
後來將ajax請求改爲同步之後,還是失敗,最後,將提交表單的方式改爲summit,成功!!!
<form action="index" id="frm"> <input type="text" name="dname"> <input type="text" name="loc"> <input type="submit" value="提交" ></form>
總結:ajax請求最好只用於發送數據,和從後端拿數據,不要做跳轉頁面的...如果一定要做頁面的跳轉,可以約定後端放回的數據爲1或0,當返回的數據爲1時,用Windows.location.href="index.html" rel="external nofollow" rel="external nofollow" 來跳轉
具體代碼如下:
function callback(dat){ if (dat=1){ window.location.href="index.html" rel="external nofollow" rel="external nofollow" }else { alert("1") }
否則就用submit提交,記住了,ajax用於發送請求到那個方法後,後端是跳轉不了頁面的,也不會報錯,因爲ajax用於默認是異步請求,如果要跳就在前端跳轉頁面也是可以的
這個坑記錄下來,爲後來的你們給與一些建議!!!
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持神馬文庫。