1 前言
在史上最簡(jiǎn)單的 Spring MVC 教程(七)中,咱們已經(jīng)實(shí)現(xiàn)了“人員列表”的修改功能,那么接下來,在本篇博文中,咱們繼續(xù)實(shí)現(xiàn)“人員列表”中人員信息的刪除功能,包括刪除單條記錄和批量刪除記錄。
2 注解示例 - 刪除
老規(guī)矩,首先給出項(xiàng)目結(jié)構(gòu)圖:
2.1 刪除單條記錄
第一步:在 Service 層(PersonService)中新建刪除單條記錄的方法
package spring.mvc.service;
import org.springframework.stereotype.Service;
import spring.mvc.domain.Person;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** * Created by 維C果糖 on 2017/1/26\. */
@Service
public class PersonService { // 模擬內(nèi)存數(shù)據(jù)庫(kù),準(zhǔn)備數(shù)據(jù)
// 聲明一個(gè)容器
private static Map<Integer, Person> map = new HashMap<Integer, Person>();
// 初始化 id
private static Integer id = 0;
// 利用靜態(tài)塊初始化數(shù)據(jù)
static {
for (int i = 0; i < 10; i++) {
Person p = new Person();
p.setId(id++);
p.setName("Charie" + i);
p.setAge(10 + i);
map.put(i, p);
}
}
// 獲取人員列表
public List<Person> findAll() {
// 將 map 對(duì)象轉(zhuǎn)換為 list 結(jié)合
return new ArrayList(map.values());
}
// 獲得一個(gè) Person 對(duì)象
public Person get(Integer id) {
return map.get(id);
}
// 新增人員信息
public void insert(Person p) {
id++;
p.setId(id);
map.put(id, p);
}
// 修改人員信息
public void update(Person p) {
map.put(p.getId(), p);
}
// 刪除單條記錄
public void deleteById(Integer id) {
map.remove(id);
}
}
第二步:在控制器(PersonController)中添加新方法
package spring.mvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import spring.mvc.domain.Person;
import spring.mvc.service.PersonService;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
/** * Created by 維C果糖 on 2017/1/26\. */
@Controller
public class PersonController {
@Resource
PersonService ps; // 注入 service 層
@RequestMapping(value = "/person/all")
public String findAll(Map<String, Object> model) { // 聲明 model 用來傳遞數(shù)據(jù)
List<Person> personList = ps.findAll();
model.put("personList", personList); // 通過這一步,JSP 頁(yè)面就可以訪問 personList
return "/person/jPersonList"; // 跳轉(zhuǎn)到 jPersonList 頁(yè)面
}
@RequestMapping("/person/toCreatePersonInfo")
public String toCteatePersonInfo() { // 跳轉(zhuǎn)新增頁(yè)面
return "/person/jPersonCreate";
}
@RequestMapping("/person/toUpdatePersonInfo")
public String toUpdatePersonInfo(Integer id, Model model) { // 跳轉(zhuǎn)修改頁(yè)面
Person p = ps.get(id); // 獲得要修改的記錄,重新設(shè)置頁(yè)面的值
model.addAttribute("p", p); // 將數(shù)據(jù)放到 response
return "/person/jPersonUpdate";
}
@RequestMapping("/person/updatePersonList")
public String updatePersonList(Person p) {
if (p.getId() == null) {
ps.insert(p); // 調(diào)用 Service 層方法,插入數(shù)據(jù)
} else {
ps.update(p); // 調(diào)用 Service 層方法,更新數(shù)據(jù)
}
return "redirect:/person/all.action"; // 轉(zhuǎn)向人員列表 action
}
@RequestMapping("/person/deleteById")
public String deleteById(Integer id){
ps.deleteById(id);
return "redirect:/person/all.action"; // 轉(zhuǎn)向人員列表 action
}
}
第三步:修改 jPersonList.jsp 頁(yè)面,添加“刪除”選項(xiàng)
<%-- Created by IntelliJ IDEA. User: 維C果糖 Date: 2017/1/27 Time: 00:00 To change this template use File | Settings | File Templates. --%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>PersonList</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/personform.action" method="post">
<div style="padding:20px;">
人員列表
</div>
<div style="padding-left:40px;">
<a href="/springmvc-annotation/person/toCreatePersonInfo.action">新增</a> <!-- 跳轉(zhuǎn)路徑 -->
</div>
<table border="1">
<tr>
<td>編號(hào)</td>
<td>姓名</td>
<td>年齡</td>
<td>操作</td>
</tr>
<c:forEach items="${personList}" var="p">
<tr>
<td>${p.id}</td>
<td>${p.name}</td>
<td>${p.age}</td>
<td>
<a href=/springmvc-annotation/person/toUpdatePersonInfo.action?id=${p.id}>修改</a>
<a href=/springmvc-annotation/person/deleteById.action?id=${p.id}>刪除</a>
</td>
</tr>
</c:forEach>
</table>
</form>
</body>
</html>
在完成以上步驟后,啟動(dòng) tomcat 服務(wù)器,然后訪問 http://localhost:8080/springmvc-annotation/person/all.action,頁(yè)面如下所示:
然后,選擇想要?jiǎng)h除的記錄,在這里,咱們選擇編號(hào)為10的記錄進(jìn)行測(cè)試,點(diǎn)擊“刪除”,頁(yè)面將會(huì)重新跳轉(zhuǎn)到 http://localhost:8080/springmvc-annotation/person/all.action,并顯示刪除記錄后的人員列表,頁(yè)面顯示如下所示:
2.2 批量刪除記錄
第一步:在控制器(PersonController)中添加批量刪除的方法
package spring.mvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import spring.mvc.domain.Person;
import spring.mvc.service.PersonService;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
/** * Created by 維C果糖 on 2017/1/26\. */
@Controller
public class PersonController {
@Resource
PersonService ps; // 注入 service 層
@RequestMapping(value = "/person/all")
public String findAll(Map<String, Object> model) { // 聲明 model 用來傳遞數(shù)據(jù)
List<Person> personList = ps.findAll();
model.put("personList", personList); // 通過這一步,JSP 頁(yè)面就可以訪問 personList
return "/person/jPersonList"; // 跳轉(zhuǎn)到 jPersonList 頁(yè)面
}
@RequestMapping("/person/toCreatePersonInfo")
public String toCteatePersonInfo() { // 跳轉(zhuǎn)新增頁(yè)面
return "/person/jPersonCreate";
}
@RequestMapping("/person/toUpdatePersonInfo")
public String toUpdatePersonInfo(Integer id, Model model) { // 跳轉(zhuǎn)修改頁(yè)面
Person p = ps.get(id); // 獲得要修改的記錄,重新設(shè)置頁(yè)面的值
model.addAttribute("p", p); // 將數(shù)據(jù)放到 response
return "/person/jPersonUpdate";
}
@RequestMapping("/person/updatePersonList")
public String updatePersonList(Person p) { // 更新人員信息
if (p.getId() == null) {
ps.insert(p); // 調(diào)用 Service 層方法,插入數(shù)據(jù)
} else {
ps.update(p); // 調(diào)用 Service 層方法,更新數(shù)據(jù)
}
return "redirect:/person/all.action"; // 轉(zhuǎn)向人員列表 action
}
@RequestMapping("/person/deleteById")
public String deleteById(Integer id){ // 刪除單條記錄
ps.deleteById(id);
return "redirect:/person/all.action"; // 轉(zhuǎn)向人員列表 action
}
@RequestMapping("/person/deleteMuch")
public String deleteMuch(@RequestParam("id") Integer[] ids){ // 批量刪除記錄
for (Integer delId : ids){
ps.deleteById(delId);
}
return "redirect:/person/all.action"; // 轉(zhuǎn)向人員列表 action
}
}
如上所示,在函數(shù) deleteMuch 中,為了保證頁(yè)面?zhèn)鬟f過來的參數(shù)與定義在控制器中的方法的參數(shù)名稱的一致性,咱們用注解 @RequestParam(“id”) 將參數(shù) ids 內(nèi)容封裝到 id 中。在這里,咱們還有另外一種參數(shù)的傳遞方式,即直接將 deleteMuch 方法中的參數(shù)類型定義為 String 類型,這樣當(dāng) Spring MVC 框架在接收到頁(yè)面?zhèn)鬟f過來的多個(gè)同名參數(shù)值后,其會(huì)用逗號(hào)將參數(shù)值依次拼接成為一個(gè)字符串。
特別注意:當(dāng)封裝多個(gè)同名參數(shù)值時(shí),如果方法中的參數(shù)類型為 Integer 、Double 或者 Date 時(shí),Spring MVC 框架為了容錯(cuò),只會(huì)保留第一個(gè)參數(shù)值,而不會(huì)拋出錯(cuò)誤。
在此,作者給出第二種傳參方法以供參考:
@RequestMapping("/person/deleteMuch")
public String deleteMuch(String id){ // 批量刪除記錄
for (String delId : id.split(",")){
ps.deleteById(Integer.parseInt(delId));
}
return "redirect:/person/all.action"; // 轉(zhuǎn)向人員列表 action
}
第二步:修改 jPersonList.jsp 頁(yè)面,添加“批量刪除”選項(xiàng)、復(fù)選框及 JavaScript 函數(shù)
<%-- Created by IntelliJ IDEA. User: 維C果糖 Date: 2017/1/29 Time: 15:30 To change this template use File | Settings | File Templates. --%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>PersonList</title>
<script language="JavaScript"> /** * 批量提交方法 */ function deleteMuch() { document.forms[0].action = "${pageContext.request.contextPath}/person/deleteMuch.action"; document.forms[0].submit(); <!-- 手動(dòng)提交 --> } </script>
</head>
<body>
<form method="post">
<div style="padding:20px;">
人員列表
</div>
<div style="padding-left:40px;padding-bottom: 10px;">
<a href="/springmvc-annotation/person/toCreatePersonInfo.action">新增</a> <!-- 跳轉(zhuǎn)路徑 -->
<a href="#" onclick="deleteMuch()">批量刪除</a> <!-- 調(diào)用 JavaScript -->
</div>
<table border="1">
<tr>
<td>選擇</td>
<td>編號(hào)</td>
<td>姓名</td>
<td>年齡</td>
<td>操作</td>
</tr>
<c:forEach items="${personList}" var="p">
<tr>
<td>
<input type="checkbox" name="id" value="${p.id}"/>
</td>
<td>${p.id}</td>
<td>${p.name}</td>
<td>${p.age}</td>
<td>
<a href=/springmvc-annotation/person/toUpdatePersonInfo.action?id=${p.id}>修改</a>
<a href=/springmvc-annotation/person/deleteById.action?id=${p.id}>刪除</a>
</td>
</tr>
</c:forEach>
</table>
</form>
</body>
</html>
在完成以上步驟后,啟動(dòng) tomcat 服務(wù)器,然后訪問 http://localhost:8080/springmvc-annotation/person/all.action,頁(yè)面如下所示:

然后,選擇想要?jiǎng)h除的記錄,在這里,咱們選擇編號(hào)為 0 和 1 的記錄進(jìn)行測(cè)試,點(diǎn)擊“批量刪除”,頁(yè)面將會(huì)重新跳轉(zhuǎn)到 http://localhost:8080/springmvc-annotation/person/all.action,并顯示批量刪除記錄后的人員列表,頁(yè)面顯示如下所示:
