大三筆記(困擾了一下午的bug,居然是路徑問題)
阿新 • • 發佈:2018-11-09
19號在寫測試ajax與controller互動時,一個bug困擾了我。
先貼程式碼。
index.jsp
<head> <title>開發中......</title> <script type="text/javascript" src="jquery-1.6.1.min.js"></script> </head> <body> <form id="form1" method="post"> <input type="text" id="student_id"> <button onclick="findStudentInfo()">哈哈</button></form> <div id="showMessageDiv"></div> </body> <script type="application/javascript"> function findStudentInfo() { // alert("as"); var student_id= 1; $.ajax({ type:'POST', url: 'http://localhost:8080/myspringTest/login.do', data:{'student_id':student_id}, dataType:"json", // traditional: true, 這裡的取值後面說明 success: function () { $("#showMessageDiv").append("<table id='table1'></table>"); $("#table1").append("<tr><td>學生ID</td><td>姓名</td><td>性別</td><td>地址</td></tr>"); }, error: function () { alert("asasq"); } }); } </script>
呃寫這個ajax主要是為了測試,不用細看。
UserController.java
package com.cn.lin.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.cn.lin.bean.student; import com.cn.lin.service.studentService; import com.cn.lin.vo.ResultVo; @Controller @RequestMapping("/") public class UserController { @Autowired private studentService service; @RequestMapping("login") @ResponseBody public ResultVo<student> login(@RequestParam("student_id")int student_id){ System.out.println("收的到"); ResultVo<student> resultVo = service.check(student_id, "as"); if(resultVo.getSuccess()){ System.out.println("As"); } return resultVo; }
程式碼貼完了,說說問題,在Index.jsp中提交表單之後,controller沒有任何反應,ajax也沒有執行error,一開始我就認為是ajax中的url問題,從url:login.do 一開始測試,最後我無奈將url寫成絕對路徑,還是不行,controller還是沒有反應,有點絕望,逛了很久論壇部落格,最後才在瀏覽器的控制檯發現,jq檔案報了404!!!!
一開始我認為jq檔案應該是放在src/main/resources路徑下的,並且認為resources路徑就是專案根路徑,但是就是找不到jq檔案,後來把jq和index.jsp放一起後,問題解決。
原因:如果我們這樣寫: url:"/login.do" ,你可能會覺得這個url是 專案根路徑/方法路徑。。。但其實這並不是專案根路徑,而是 http://localhost:8080/路徑
所以這裡url應寫成 /專案名/login.do
而jq檔案找不到的原因呢:
src/main/resources
下的靜態資源要被編譯進入專案名\target\classes
才能被外部訪問,而src/main/webapp
下的靜態資源,無需編譯可以直接被訪問到