繼0730,我們對項目做最后的升級
一、刪除功能
1、新增復選框輔助刪除條目的選擇
修改我們的list.jsp和list.js在列表的第一列增加一列選擇框
??2、給復選框添加全選與行點擊選擇功能
在行選擇功能中,因為此時的選擇框還未生成,所以我們將事件委托給他的父類“#tab”
//全選與取消全選$("#checkAll").click(function (){let checked = $(this).prop("checked");$("#tab>tbody>tr>td:first-child>:checkbox").prop("checked",checked);});//點擊行選中 事件委托$("#tab").on("click","tr>td:not(:first-child)",function (){let $tr = $(this).parent();const $chk = $tr.children().first().children()const check = $chk.prop("checked");$chk.prop("checked",!check);})
?3、給刪除按鈕添加事件
let $checked = $("#tab tr>td:first-child>:checked")獲取當前全部被選擇的選擇框的狀態,如果存在選中,使用layer.confirm創建一個帶有“確定”和“取消”按鈕的確認對話框。
通過.each將$checked中的每個data-id值都存到ids中,將ids傳給函數delectById.
//刪除按鈕事件$("#del").click(function (){let $checked = $("#tab tr>td:first-child>:checked")//console.log($checked);if($checked.length === 0){layer.msg("請選擇要刪除的學生");}else{layer.confirm("你確定你要刪除選中的行嗎", function (handler){//刪除所有選中的行let ids = [];$checked.each(function (idx,item){console.log(idx,item);ids.push(parseInt($(item).attr("data-id")));});console.log(ids);deleteByIds(ids, function (count){if(count>0){layer.msg("成功刪除"+count+"行數據");findAll(currentPage,limits);}else{layer.msg("刪除失敗");}});layer.close(handler)});}})
?4、創建函數delectById將ids值傳到后端
以post形式傳到delete地址下,通過后端刪除后返回給回調函數rows值,再將rows傳回給按鈕。
//參數為id數組
function deleteByIds(ids, cb=$.noop) {//請求、響應模型$.ajax({url: ctx + "/student/delete",method: "post",//添加此屬性,表示可以向后臺傳遞數組參數traditional: true,data: {ids},success: function (resp){cb(resp.rows);}})
}
5、select接收請求向下調用
list.js->select->service->dao? --->selcet->list.js->list.jsp
private void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//獲取請求參數中的idsString[] strIds = req.getParameterValues("ids");//將ids轉換為List<Integer>List<Integer> ids = new ArrayList<>();for(int i=0;i<strIds.length;i++) ids.add(Integer.parseInt(strIds[i]));//調用studentService的deleteByIds方法刪除數據,返回刪除的行數int rows = studentService.deleteByIds(ids);//將刪除的行數封裝到map中Map<String, Object> map = Map.of("rows", rows);ServletUtil.renderJson(resp,map);}
?在dao中編寫sql語句訪問數據庫
public int deleteByIds(List<Integer> ids) {//sparing提供的模板工具類JdbcTemplate jdbcTemplate = Global.getTemplate();//判斷ids是否為空if(ids == null || ids.isEmpty()) return -1;//創建StringBuilder對象StringBuilder sb = new StringBuilder();//使用repeat方法重復添加"?,"sb.append("?,".repeat(ids.size()));//截取最后一個","String ph = sb.substring(0, sb.length()-1);//拼接刪除語句String delsql = "delete from t_student where id in ("+ph+")";//執行刪除語句int rows = jdbcTemplate.update(delsql, ids.toArray());return rows;}
?成功獲取刪除條數,將rows編寫成json語句返回前端,這里我們新建一個工具類ServletUtil用于返回json
package com.situ.util;import com.alibaba.fastjson2.JSON;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;import java.io.IOException;
import java.io.PrintWriter;public class ServletUtil {//將對象轉換為json字符串并寫入響應流public static void renderJson(HttpServletResponse resp, Object obj) throws IOException {//設置響應的內容類型為jsonresp.setContentType("application/json;charset=UTF-8");//獲取響應的輸出流PrintWriter out = resp.getWriter();//將map轉換為json字符串并寫入響應流out.write(JSON.toJSONString(obj));//刷新響應流out.flush();}
}
二、新增功能
1.為新增按鈕添加事件
按鈕打開一個懸浮窗,窗內顯示add頁面,
- 參數說明:
handler
: 當前彈窗的索引(index),用于關閉彈窗。$jq
: 表示彈窗的 jQuery 對象(包含整個 layer DOM 結構)。
- 在彈窗中查找?
iframe
?元素。 - 獲取其原生 DOM 元素(
[0]
)。 - 然后通過?
.contentWindow
?獲取?iframe 內部頁面的 window 對象。 - 這樣就可以調用 iframe 內部的 JavaScript 函數了。
- 調用 iframe 內部頁面的?
submit()
?函數。 submit
?函數接收一個回調函數作為參數,用于接收提交結果(success
?是布爾值)。- 如果?
success
?為?true
:- 顯示“新增成功”提示。
- 調用?
findAll(...)
?刷新當前學生列表。 - 關閉彈窗(
layer.close(handler)
)。
- 如果?
success
?為?false
:- 提示用戶“新增失敗”,并檢查數據。
$("#add").click(function (){layer.open({title: "新增學生",type: 2,area: ["800px","600px"],btn: ["確定","取消"],content: ctx + "/student/add",yes: function (handler, $jq){const win= $jq.find("iframe")[0].contentWindow;win.submit(function (success){if(success){layer.msg("新增成功");findAll(currentPage,limits);layer.close(handler);}else {layer.msg("新增失敗,請修改不合格數據");}});}})});
?2、新建add功能的jsp、css、js
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="jakarta.tags.core"%><c:set var="cxt" value="${pageContext.request.contextPath}"/>
<html>
<head><base href="${cxt}/"><title>新增學生數據</title><link rel="stylesheet" href="assets/modules/student/css/add.css"><link rel="stylesheet" href="assets/lib/layui/css/layui.css"><script src="assets/lib/jquery/jquery-3.7.1.min.js"></script><script src="assets/modules/student/js/add.js"></script><script src="assets/lib/layui/layui.js"></script><script>const ctx = "${cxt}";</script>
</head>
<body><form id="student-form" action=""><div><label for="stuId">學號:</label><input type="text" name="stuId" id="stuId" autocomplete="off" placeholder="請輸入學號"></div><div><label for="name">姓名:</label><input type="text" name="name" id="name" autocomplete="off" placeholder="請輸入姓名"></div><div><label for="pinyin">拼音:</label><input type="text" name="pinyin" id="pinyin" autocomplete="off" placeholder="請輸入拼音"></div><div><label for="sex">性別:</label><input type="radio" name="sex" id="male" value="男" checked><label for="male">男</label><input type="radio" name="sex" id="female" value="女"><label for="female">女</label></div><div><label for="birthday">出生日期:</label><input type="text" name="birthday" id="birthday" autocomplete="off" placeholder="請輸入出生日期" readonly></div><div><label for="phone">手機號:</label><input type="text" name="phone" id="phone" autocomplete="off" placeholder="請輸入手機號"></div><div><label for="email">郵箱:</label><input type="text" name="email" id="email" autocomplete="off" placeholder="請輸入郵箱"></div></form>
</body>
</html>
body{padding: 10px;
}#student-form>div{margin: 20px 0;height: 50px;
}#student-form>div>label:first-child{display: inline-block;width: 100px;text-align: right;
}#student-form>div>input:not(#male,#female){outline: none;width: 300px;height: 30px;margin-left: 10px;border: 1px solid #ccc;border-radius: 5px;padding-left: 10px;
}#student-form>div>label{display: inline-block;font-size: 20px;font-weight: bold;text-align: center;
}
$(()=>{//渲染出生日期layui.use(function () {const laydate = layui.laydate;laydate.render({elem: "#birthday",type: "date"});});
});function submit(cb = $.noop){let stuId = $("#stuId").val();let name = $("#name").val();let pinyin = $("#pinyin").val();let birthday = $("#birthday").val();let phone = $("#phone").val();let email = $("#email").val();let sex = $(":input[name=sex]:checked").val();// console.log(sex);//前端校驗:js校驗if (stuId.trim() === "") {layer.msg("學號不可為空");return;}if (name.trim() === "") {layer.msg("姓名不可為空");return;}let pat = /^\d{4}-\d{2}-\d{2}$/;if (!pat.test(birthday)) {layer.msg("出生日期格式不正確");return;}pat = /^\d{11}$/;if (!pat.test(phone)) {layer.msg("手機號格式不正確");return;}$.ajax({url: "student/add",type: "post",data: {stuId,name,pinyin,birthday,phone,email,sex},success: function (resp){cb(resp.success)}})
}
?3、submit函數實現將“增加”內容發送到后端進行寫入
servlet將傳入的信息保存到Student對象中,并向下傳遞調用
private void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {req.setCharacterEncoding("UTF-8");String stuId = req.getParameter("stuId");String name = req.getParameter("name");String pinyin = req.getParameter("pinyin");String sex = req.getParameter("sex");String birthday = req.getParameter("birthday");String phone = req.getParameter("phone");String email = req.getParameter("email");//后端校驗if (!StringUtils.hasText(stuId)){ServletUtil.renderJson(resp, Map.of("error", "學號不可為空"));return;}if(!StringUtils.hasText(name)){ServletUtil.renderJson(resp, Map.of("error", "姓名不可為空"));return;}if(!phone.matches("^\\d{11}$")){ServletUtil.renderJson(resp, Map.of("error", "手機號格式不正確"));return;}Student student = new Student();student.setStuId(stuId);student.setName(name);student.setPinyin(pinyin);if(!sex.equals("男") && !sex.equals("女")){ServletUtil.renderJson(resp, Map.of("error", "性別只能是男或女"));}student.setSex(sex);try {LocalDate ld = LocalDate.parse(birthday, DateTimeFormatter.ofPattern("yyyy-MM-dd"));student.setBirthday(ld);} catch (Exception e) {ServletUtil.renderJson(resp, Map.of("error", "出生日期不正確"));}student.setPhone(phone);student.setEmail(email);boolean success = studentService.save(student);ServletUtil.renderJson(resp, Map.of("success", success));}
?Dao
public int save(Student student) {JdbcTemplate jdbcTemplate = Global.getTemplate();String sql = "insert into t_student (stu_id, name, pinyin, sex, birthday, phone, email) values(?,?,?,?,?,?,?)";int rows = jdbcTemplate.update(sql, student.getStuId(), student.getName(), student.getPinyin(), student.getSex(), student.getBirthday(), student.getPhone(), student.getEmail());return rows;}
三、修改功能
修改功能類似于增加功能,也需要新建jsp、css、js,在list.js中實現按鈕功能
這里的url將id值傳給了servlet中的doGet,get轉發到jsp,jsp設為全局常量,js就可以獲取id值
$("#edit").click(function (){let $checked = $("#tab tr>td:first-child>:checked");if($checked.length === 0) layer.msg("請選擇要編輯的學生");else if($checked.length > 1) layer.msg("一次只能編輯一個學生");else{let $id = $checked.attr("data-id");layer.open({title: "修改學生",type: 2,area: ["800px","600px"],btn: ["確定","取消"],content: ctx + "/student/edit?id="+ $id,yes: function (handler, $jq){const win= $jq.find("iframe")[0].contentWindow;win.submit(function (success){if(success){layer.msg("修改成功");findAll(currentPage,limits);layer.close(handler);}else {layer.msg("修改失敗,請修改不合格數據");}});}})}});
在js中設置findId函數用于向后端請求尋找目標id的數據,回調函數用于后端返回對應值
$(()=>{findById(id)//渲染出生日期layui.use(function () {const laydate = layui.laydate;laydate.render({elem: "#birthday",type: "date"});});
});//查詢指定id學生的信息
function findById(id){$.ajax({url: "student/id",method:"get",data:{id},success: function (resp){const stu = resp.student;$("#stuId").val(stu.stuId);$("#name").val(stu.name);$("#pinyin").val(stu.pinyin);$("#birthday").val(stu.birthday);$("#phone").val(stu.phone);$("#email").val(stu.email);$(":radio[name=sex][value="+stu.sex+"]").prop("checked",true);}})
}//修改數據提交
function submit(cb = $.noop){let stuId = $("#stuId").val();let name = $("#name").val();let pinyin = $("#pinyin").val();let birthday = $("#birthday").val();let phone = $("#phone").val();let email = $("#email").val();let sex = $(":input[name=sex]:checked").val();// console.log(sex);//前端校驗:js校驗if (stuId.trim() === "") {layer.msg("學號不可為空");return;}if (name.trim() === "") {layer.msg("姓名不可為空");return;}let pat = /^\d{4}-\d{2}-\d{2}$/;if (!pat.test(birthday)) {layer.msg("出生日期格式不正確");return;}pat = /^\d{11}$/;if (!pat.test(phone)) {layer.msg("手機號格式不正確");return;}$.ajax({url: "student/edit",type: "post",data: {id,stuId,name,pinyin,birthday,phone,email,sex},success: function (resp){cb(resp.success)}})
}
servlet中的doGet方法,調用findById方法
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {String action = req.getPathInfo();if("/list".equals(action)){//List<Student> students = studentService.findAll();//req.setAttribute("students", students);//String page = req.getParameter("page");//String limit = req.getParameter("limit");req.getRequestDispatcher("/WEB-INF/jsp/student/list.jsp").forward(req,resp);} else if("/add".equals(action)){req.getRequestDispatcher("/WEB-INF/jsp/student/add.jsp").forward(req,resp);} else if("/edit".equals(action)) {//編輯String id = req.getParameter("id");req.setAttribute("id", id);req.getRequestDispatcher("/WEB-INF/jsp/student/edit.jsp").forward(req, resp);} else if("/id".equals(action)) {//根據id查詢String id = req.getParameter("id");Student stu = studentService.findById(Integer.parseInt(id));ServletUtil.renderJson(resp, Map.of("student", stu));}}
public Student findById(Integer id) {JdbcTemplate jdbcTemplate = Global.getTemplate();String sql = "select id, stu_id, name, sex, birthday, pinyin, phone, email, qq, wechat from t_student where id = ?";Student student = jdbcTemplate.queryForObject(sql, rowMapper, id);return student;}
將對應id的目標數據顯示在浮窗中
信息修改后點擊確定按鈕,調用submit函數,在后端進行修改sql語句
private void edit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {req.setCharacterEncoding("UTF-8");String id = req.getParameter("id");String stuId = req.getParameter("stuId");String name = req.getParameter("name");String pinyin = req.getParameter("pinyin");String sex = req.getParameter("sex");String birthday = req.getParameter("birthday");String phone = req.getParameter("phone");String email = req.getParameter("email");//后端校驗if (!StringUtils.hasText(stuId)){ServletUtil.renderJson(resp, Map.of("error", "學號不可為空"));return;}if(!StringUtils.hasText(name)){ServletUtil.renderJson(resp, Map.of("error", "姓名不可為空"));return;}if(!phone.matches("^\\d{11}$")){ServletUtil.renderJson(resp, Map.of("error", "手機號格式不正確"));return;}if(!sex.equals("男") && !sex.equals("女")){ServletUtil.renderJson(resp, Map.of("error", "性別只能是男或女"));}Student student = new Student();student.setId(Integer.parseInt(id));student.setStuId(stuId);student.setName(name);student.setPinyin(pinyin);student.setSex(sex);try {LocalDate ld = LocalDate.parse(birthday, DateTimeFormatter.ofPattern("yyyy-MM-dd"));student.setBirthday(ld);} catch (Exception e) {ServletUtil.renderJson(resp, Map.of("error", "出生日期不正確"));}student.setPhone(phone);student.setEmail(email);boolean success = studentService.edit(student);ServletUtil.renderJson(resp, Map.of("success", success));}
public int edit(Student student) {JdbcTemplate jdbcTemplate = Global.getTemplate();String sql = "update t_student set stu_id = ?, name = ?, pinyin = ?, sex = ?, birthday = ?, phone = ?, email = ? where id = ?";int rows = jdbcTemplate.update(sql, student.getStuId(), student.getName(), student.getPinyin(), student.getSex(), student.getBirthday(), student.getPhone(), student.getEmail(), student.getId());return rows;}