SpringMVC?RESTFul實戰(zhàn)案例修改功能實現(xiàn)
SpringMVC RESTFul實現(xiàn)修改功能
一、回顯功能
做實際修改操作之前,需要有個回顯功能,就是點編輯頁后可以看到數(shù)據(jù)。
1.修改操作超鏈接
這里的請求地址跟刪除的一樣,需要帶上 id,因為要回顯這個 id 的數(shù)據(jù)。
<td> <a @click="deleteEmployee" th:href="@{/employee/} + ${employee.id}" rel="external nofollow" >刪除</a> <a th:href="${/employee/} + ${employee.id}" rel="external nofollow" >更新</a> </td>
重新部署后,鼠標移動到更新按鈕上,瀏覽器左下角同樣可以顯示出請求的地址。
2.處理控制器方法
因為這個回顯操作請求,不僅僅是做視圖的返回,還要去獲取 id 下的信息,所以這里不能通過配置 view-controller 來實現(xiàn)了,需要編寫控制器方法。
繼續(xù)在類 EmployeeController 下新增方法:
@RequestMapping(value = "/employee/{id}", method = RequestMethod.GET) public String getEmployeeById(@PathVariable("id") Integer id, Model model) { Employee employee = employeeDao.get(id); model.addAttribute("employee", employee); return "employee_update"; }
這里除了 id,還有個形參 model,因為需要把查詢到的數(shù)據(jù)共享到 request 域中。最后返回修改頁。
3.創(chuàng)建修改頁面
新建 employee_update.html,可以拷貝新增頁的然后修改:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>更新員工</title> </head> <body> <form th:action="@{/employee}" method="post"> <input type="hidden" name="_method" value="put"> <input type="hidden" name="id" th:value="${employee.id}"> lastName:<input type="text" name="lastName" th:value="${employee.lastName}"><br> email:<input type="text" name="email" th:value="${employee.email}"><br> gender:<input type="radio" name="gender" value="1" th:field="${employee.gender}">male <input type="radio" name="gender" value="0" th:field="${employee.gender}">female<br> <input type="submit" value="更新"><br> </form> </body> </html>
因為需要回顯,所以還要加 value 的值,比如th:value="${employee.id}"。
另外,這里有 2 個隱藏域:
<input type="hidden" name="id" th:value="${employee.id}">,用來存放 id。
<input type="hidden" name="_method" value="put">,用于發(fā)送 put 請求。
重新部署測一下,點擊更新按鈕:
回顯成功。
二、修改功能
1.添加控制器方法
@RequestMapping(value = "/employee", method = RequestMethod.PUT) public String updateEmployee(Employee employee) { employeeDao.save(employee); return "redirect:/employee"; }
調(diào)用 dao 里的 save() 方法,最后重定向到列表頁。
2.測試效果
重新部署后,點擊更新,修改3個數(shù)據(jù)測試下效果。
以上就是SpringMVC RESTFul實戰(zhàn)案例修改功能實現(xiàn)的詳細內(nèi)容,更多關于SpringMVC RESTFul修改的資料請關注腳本之家其它相關文章!
- SpringMVC?Restful風格與中文亂碼問題解決方案介紹
- SpringMVC通過RESTful結(jié)構(gòu)實現(xiàn)頁面數(shù)據(jù)交互
- SpringMVC?RESTFul及REST架構(gòu)風格介紹
- SpringMVC?RESTFul實體類創(chuàng)建及環(huán)境搭建
- SpringMVC?RESTFul實戰(zhàn)案例訪問首頁
- SpringMVC?RESTFul實現(xiàn)列表功能
- SpringMVC?RESTFul實戰(zhàn)案例刪除功能實現(xiàn)
- 關于SpringMVC對Restful風格的支持詳解
- SpringMVC使用RESTful接口案例詳解
相關文章
SpringBoot2.7?WebSecurityConfigurerAdapter類過期配置
這篇文章主要為大家介紹了SpringBoot2.7中WebSecurityConfigurerAdapter類過期應該如何配置,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-06-06Mybatis Generator自動生成對應文件的實現(xiàn)方法
這篇文章主要介紹了Mybatis Generator自動生成對應的文件的實現(xiàn)方法,需要的朋友可以參考下2017-09-09Springboot 使用內(nèi)置tomcat禁止不安全HTTP的方法
這篇文章主要介紹了Springboot 使用內(nèi)置tomcat禁止不安全HTTP的方法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07Windows7下的Java運行環(huán)境搭建過程圖解
這篇文章主要介紹了Windows7下的Java運行環(huán)境搭建過程圖解,需要的朋友可以參考下2014-04-04