目录
一、前端代码
1.样式展示
2.代码详解
<1>主页面列表部分
(1)template部分
(2)script部分
<2>新增页面
(1)template部分
(2)script部分
<3>修改页面
二、后端代码
(1)Servlet层
1.doGet方法
2.doPost方法
3.doGet中的方法
<1>查询学生列表
<2>查询专业列表
<3>删除学生
<4>查找所需内容
(2)model层
(3)Dao层
1.查询学生列表
2.查询专业列表
3.删除学生
4.新增学生
5.查询所需的学生信息
6.修改学生
在此系统中,操作界面大致相同,本篇将以学生管理的操作页面为例进行代码详解,在其他不同的操作页面有不同的情况下也会进行详解。
一、前端代码
1.样式展示
2.代码详解
<1>主页面列表部分
(1)template部分
<template><el-card class="box-card"><!-- 卡片 --><div slot="header" class="clearfix"><span>学生列表</span><el-button style="float: right; padding: 3px 0" type="text" @click="openDialog()">新增<i class="el-icon-circle-plus-outline el-icon--right"></i></el-button></div><el-table :data="tableList" border :stripe="true" style="width: 100%"><!-- stripe:斑马纹 --><el-table-column type="index" label="序号" width="60" align="center"></el-table-column><el-table-column prop="num" label="学号" width="100" sortablealign="center"></el-table-column><!-- sortable排序 --><el-table-column prop="name" label="姓名" width="100" align="center"></el-table-column><el-table-column prop="gender" label="性别" width="50" align="center":resizable="false"></el-table-column><!-- resizable禁止拖拽 --><el-table-column prop="birthday" label="生日" align="center"></el-table-column><el-table-column prop="phone" label="电话" align="center"></el-table-column><el-table-column prop="mname" label="专业" align="center"></el-table-column><el-table-column prop="account" label="操作人" align="center"></el-table-column><el-table-column prop="operTime" label="操作时间" align="center" sortable></el-table-column><el-table-column label="操作" align="center"><template slot-scope="scope"><el-button size="mini" @click="openUpdateDialog(scope.row.id)">编辑</el-button><!-- scope.row获取到你所点击的那一行的数据 --><el-button size="mini" type="danger" @click="deletestudent(scope.row.id)">删除</el-button></template></el-table-column></el-table><add ref="add"></add><!-- 使用组件 --><update ref="update"></update></el-card>
</template>
利用element-UI组件中的布局进行修改,已达到目的要求样式
注意最后的部分是用来调用新增,修改的组件的
(2)script部分
<script>/* 导入其他组件 */import add from "./add.vue";import update from "./update.vue";export default {components: { //注册组件add,update},data() {return {tableList: []}},methods: {openDialog() {//在父组件操作子组件this.$refs.add.dialogVisible = true;},openUpdateDialog(id){this.$refs.update.dialogVisible = true;this.$refs.update.findStudentById(id);},deletestudent(id) {this.$confirm('您确定要删除吗?', '提示', {confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning'}).then(() => {//向后端发送请求,并返回id到后端this.$http.get("/api/student?mark=deletestudent&id=" + id).then((resp) => {if (resp.data.code == 200) {this.$message({type: 'success',message: '删除成功!'});this.$router.go(0);}})})}},mounted() {//打开组件后自动向后端发送一个查询学生列表的请求this.$http.get("api/student?mark=studentlist").then((resp) => {if (resp.data.code == 200) {//接收后端响应的数据this.tableList = resp.data.result;//把学生信息显示到数据表格中}})}}
</script>
1. 在进行增加和修改的操作时,会弹出一个窗口来进行操作,我们将这部分的代码重新放在一个vue中调用来使用。
正常的调用其他vue需要重新打开一个新窗口,而此方法可以在原本的额网页基础上弹出浮窗来显示vue中的内容。
用import...from...来进行调用,并在temp中进行调用
<add ref="add"></add>
<update ref="update"></update> import add from "./add.vue";
import update from "./update.vue";
2.openDialog() 用来显示出弹窗,改变dialogVisible的boolean值来使得弹窗显示和消失(点击修改操作时类似)
3.在进行删除操作时,我们需要获取到当前的id,以id来对数据库内的数据进行删除,而获取方法即:
scope.row.id
在scope中获取点击的这一行(row)的id
4.在进行删除操作时,要进行提示,确定用户是否要进行删除操作,删除成功后也要进行提示
deletestudent(id) {this.$confirm('您确定要删除吗?', '提示', {confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning'}).then(() => {//向后端发送请求,并返回id到后端this.$http.get("/api/student?mark=deletestudent&id=" + id).then((resp) => {if (resp.data.code == 200) {this.$message({type: 'success',message: '删除成功!'});this.$router.go(0);}})})}
this.$router.go(0)是为了关闭提示信息的。
''/api/student?mark=deletestudent&id=" + id
是用来与后端连接的,在后端中,给servlet中命名
@WebServlet(urlPatterns = "/api/student")在前端需要后端的doget或dopost方法时,即可用/api/student来对后端进行连接
但是前端不止需要一个doget方法,所以还需要对每个不同的方法“起名”mark=deletestudent
后端在doget方法中接收不同的Mark,来执行不同的方法。
String mark = req.getParameter("mark"); if (mark.equals("studentlist")) {findStudents(req, resp); }而有些需要给后端传值,比如上面需要传id值进行查询,就在后面将id值传到后端&id=" + id
后端需要进行接收id,进行查询即可
String id = req.getParameter("id");
5.mounted()是打开组件就进行的函数操作,将查询学生列表的函数放在其中进行查询,即可直接显示出学生列表
mounted() {//打开组件后自动向后端发送一个查询学生列表的请求this.$http.get("api/student?mark=studentlist").then((resp) => {if (resp.data.code == 200) {//接收后端响应的数据this.tableList = resp.data.result;//把学生信息显示到数据表格中}})}
<2>新增页面
(1)template部分
<template><!-- 新增代码内容是比较多的,建议抽取出来,定义到一个独立的vue文件中在列表组件中导入添加组件--><el-dialog title="新增学生" :visible.sync="dialogVisible" width="50%"><el-form ref="form" label-width="80px"><el-form-item label="学号"><el-input v-model="form.num"></el-input></el-form-item><el-form-item label="姓名"><el-input v-model="form.name"></el-input></el-form-item><el-form-item label="性别"><el-radio-group v-model="form.gender"><el-radio label="男"></el-radio><el-radio label="女"></el-radio></el-radio-group></el-form-item><el-form-item label="生日"><el-date-picker type="date" placeholder="选择日期" v-model="form.birthday" style="width: 100%;"value-format="yyyy-MM-dd" :picker-options="pickerOptions"></el-date-picker></el-form-item><el-form-item label="电话"><el-input v-model="form.phone"></el-input></el-form-item><el-form-item label="地址"><el-input v-model="form.address"></el-input></el-form-item><el-form-item label="专业"><el-select placeholder="请选择" v-model="form.majorid"><el-option v-for="major in majorlist" :key="major.id" :label="major.name" :value="major.id"></el-option></el-select></el-form-item></el-form><span slot="footer" class="dialog-footer"><el-button @click="dialogVisible = false">取 消</el-button><el-button type="primary" @click="save()">保 存</el-button></span></el-dialog>
</template>
利用elem-UI中的表单组件进行修改,添加所需元素。
(2)script部分
<script>export default {data() {return {pickerOptions: {disabledDate(time) {return time.getTime() > Date.now() - 8.64e6; //如果没有后面的-8.64e6就是不可以选择今天的}},dialogVisible: false,majorlist: [],form: {num: "",name: "",gender: "",birthday: "",phone: "",majorid: ""}}},methods: {save() {this.$http.post("api/student", jsonToString(this.form)).then((resp) => {if (resp.data.code == 200) {this.$message({message:resp.data.desc,type:'success'});this.dialogVisible = false;this.$router.go(0);}})}},mounted() {//向后端发送一个请求,查询专业信息this.$http.get("api/student?mark=majorlist").then((resp) => {if (resp.data.code == 200) {this.majorlist = resp.data.result;}})}}//将json对象序列化为 键=值&键=值function jsonToString(form) {var str = "";for (var s in form) {str += s + "=" + form[s] + "&";}return str.substring(0, str.length - 1);}
</script>
1.pickerOptions中的disabledDate(time)是用来更改时间格式的,因为在后端查询出来的时间指的是从1979到现在的毫秒值,我们需要转换格式将其显示到前端上去。
2.this.$http.post("api/student", jsonToString(this.form))调用的是后端的dopost方法,将form中的值传给后端进行保存。
3.在新增中,我们需要知道所有专业信息,将专业信息放在下拉框中,才能新增学生信息时,给学生选定专业。所以我们需要查询专业信息,将查到的信息放在majorlist中,赋到专业下拉框中。
<3>修改页面
修改页面与新增页面相同,不同的是需要在修改页面中把选中的那个学生的信息显示到修改页面当中,所以需要在点开页面时进行一次查询,将内容赋到页面上去
findStudentById(id){//向后端发送请求this.$http.get("api/student?mark=findstudent&id="+id).then((resp) => {if (resp.data.code == 200) {this.form=resp.data.result;}})}
在学生列表(主页面)中,点击编辑按钮,调用openUpdateDialog(scope.row.id)函数,并将获取到的id传到findStudentById(id)中,在编辑页面进行执行,向后端传入id值,利用id查询学生信息,传回到前端中。
二、后端代码
(1)Servlet层
1.doGet方法
@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System.out.println("student doget");String mark = req.getParameter("mark");if (mark.equals("studentlist")) {findStudents(req, resp);}if (mark.equals("majorlist")) {findMajors(req, resp);}if(mark.equals("deletestudent")){deleteStudent(req,resp);}if(mark.equals("findstudent")){findStudent(req,resp);}}
doget方法:因为前端传回来不同的doget请求,所以将给个请求分到不同的方法中,然后在doget中调用即可。
2.doPost方法
@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {String id=req.getParameter("id");//新增时,请求中没有id,修改时请求中有idString num = req.getParameter("num");String name = req.getParameter("name");String gender = req.getParameter("gender");String birthday = req.getParameter("birthday");String phone = req.getParameter("phone");String address = req.getParameter("address");String majorid = req.getParameter("majorid");String token = req.getHeader("token");//操作人idDecodedJWT decodedJWT = JWTUtil.getTokenInfo(token);int adminid = decodedJWT.getClaim("id").asInt();//调用dao层,将接收到的数据保存到数据库StudentDao studentDao = new StudentDao();Result result;try {if(id==null){studentDao.insertStudent(num, name, gender, birthday, phone, address, majorid, adminid);}else{studentDao.updateStudent(id, name, gender, birthday, phone, address, majorid, adminid);}result = new Result(200, "保存成功", null);} catch (SQLException throwables) {throwables.printStackTrace();result = new Result<>(500, "保存失败", null);}//向前端作出响应resp.getWriter().print(new ObjectMapper().writeValueAsString(result));}
doPost方法中,需要先接收前端传过来的数据(form中的数据),然后根据这些数据进行下一步的操作。
前端向后端发送的doPost请求也有两种,一种是新增学生内容,将新增的内容传给后端,一种是修改内容,将修改后的内容传给后端。因为两种请求的区别在于有没有传给后端id值,所以只需要在doPost中判断是否接受了id值,来进行不同的方法。
后端与数据库连接的部分在dao中,所以将方法放在dao中,在Servlet中调用dao中的方法。
3.doGet中的方法
<1>查询学生列表
/*查询学生列表*/public void findStudents(HttpServletRequest req, HttpServletResponse resp) throws IOException {StudentDao studentDao = new StudentDao();Result result;try {ArrayList<Student> students = studentDao.findStudents();result = new Result(200, "查询成功", students);} catch (SQLException throwables) {throwables.printStackTrace();result = new Result(500, "系统忙", null);}resp.getWriter().print(new ObjectMapper().writeValueAsString(result));}
<2>查询专业列表
/*查询专业列表*/public void findMajors(HttpServletRequest req, HttpServletResponse resp) throws IOException {StudentDao studentDao = new StudentDao();Result result;try {ArrayList<Major> majors = studentDao.findMajors();result = new Result(200, "查询成功", majors);} catch (SQLException throwables) {throwables.printStackTrace();result = new Result(500, "系统忙", null);}resp.getWriter().print(new ObjectMapper().writeValueAsString(result));}
<3>删除学生
/*删除学生*/public void deleteStudent(HttpServletRequest req, HttpServletResponse resp) throws IOException {StudentDao studentDao = new StudentDao();Result result;try {String id = req.getParameter("id");studentDao.deleteStudent(id);result = new Result(200, "删除成功", null);} catch (SQLException throwables) {throwables.printStackTrace();result = new Result(500, "系统忙", null);}resp.getWriter().print(new ObjectMapper().writeValueAsString(result));}
<4>查找所需内容
private void findStudent(HttpServletRequest req, HttpServletResponse resp) throws IOException {StudentDao studentDao = new StudentDao();Result result;try {String id = req.getParameter("id");Student student=studentDao.findstudent(id);result = new Result(200, "查询1成功", student);} catch (SQLException throwables) {throwables.printStackTrace();result = new Result(500, "系统忙", null);}resp.getWriter().print(new ObjectMapper().writeValueAsString(result));}
(2)model层
在model层中,需要将所需的数据都表示出来,封装到一个类中,方便后面的调用。
package com.ffyc.dormserver.model;import com.fasterxml.jackson.annotation.JsonFormat;import java.sql.Timestamp;
import java.util.Date;public class Student {private int id;private int num;private String name;private String gender;@JsonFormat(pattern ="yyy-MM-dd",timezone = "GMT+8")//后端把对象转为json时,把日期格式化private Date birthday;private String phone;private String mname;private String address;private int majorid;private String account;@JsonFormat(pattern ="yyy-MM-dd HH:mm:ss",timezone = "GMT+8")private Date operTime;public int getId() {return id;}public void setId(int id) {this.id = id;}public int getNum() {return num;}public void setNum(int num) {this.num = num;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getGender() {return gender;}public void setGender(String gender) {this.gender = gender;}public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;}public String getPhone() {return phone;}public void setPhone(String phone) {this.phone = phone;}public String getMname() {return mname;}public void setMname(String mname) {this.mname = mname;}public String getAccount() {return account;}public void setAccount(String account) {this.account = account;}public Date getOperTime() {return operTime;}public void setOperTime(Date operTime) {this.operTime = operTime;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}public int getMajorid() {return majorid;}public void setMajorid(int majorid) {this.majorid = majorid;}
}
(3)Dao层
Dao层就是后端与数据库进行连接的地方,所有SQL语句都在这里面
1.查询学生列表
public ArrayList<Student> findStudents() throws SQLException {ArrayList<Student> students = new ArrayList<>();PreparedStatement ps = null;Connection connection = null;try {connection = JDBCUtil.GetConnection();ps = connection.prepareStatement("SELECT\n" +"s.id,\n" +"s.num,\n" +"s.name,\n" +"s.gender,\n" +"s.birthday,\n" +"s.phone,\n" +"m.name mname,\n" +"a.account,\n" +"s.oper_time\n" +"FROM student s LEFT JOIN major m ON s.majorid=m.id\n" +"LEFT JOIN admin a ON s.adminid=a.id");ResultSet rs = ps.executeQuery();while (rs.next()) {Student student = new Student();student.setId(rs.getInt("id"));student.setNum(rs.getInt("num"));student.setName(rs.getString("name"));student.setGender(rs.getString("gender"));student.setBirthday(rs.getDate("birthday"));student.setPhone(rs.getString("phone"));student.setMname(rs.getString("mname"));student.setAccount(rs.getString("account"));student.setOperTime(rs.getTimestamp("oper_time"));students.add(student);}} finally {JDBCUtil.close(connection, ps);}return students;}
2.查询专业列表
public ArrayList<Major> findMajors() throws SQLException {ArrayList<Major> majors = new ArrayList<>();PreparedStatement ps = null;Connection connection = null;try {connection = JDBCUtil.GetConnection();ps = connection.prepareStatement("SELECT id,name FROM major");ResultSet rs = ps.executeQuery();while (rs.next()) {Major major = new Major();major.setId(rs.getInt("id"));major.setName(rs.getString("name"));majors.add(major);}} finally {JDBCUtil.close(connection, ps);}return majors;}
3.删除学生
public void deleteStudent(String id) throws SQLException {System.out.println("deletestudent");PreparedStatement ps = null;Connection connection = null;try {connection = JDBCUtil.GetConnection();ps = connection.prepareStatement("delete from student where id = ?");ps.setObject(1, id);ps.executeUpdate();} finally {JDBCUtil.close(connection, ps);}}
4.新增学生
public boolean insertStudent(String num, String name, String gender, String birthday, String phone, String address, String majorid, int adminid) throws SQLException {System.out.println("insertstudent");PreparedStatement ps = null;Connection connection = null;try {connection = JDBCUtil.GetConnection();ps = connection.prepareStatement("insert into student (num,name,gender,birthday,phone,address,majorid,adminid,oper_time)values(?,?,?,?,?,?,?,?,now())");ps.setObject(1, num);ps.setObject(2, name);ps.setObject(3, gender);ps.setObject(4, birthday);ps.setObject(5, phone);ps.setObject(6, address);ps.setObject(7, majorid);ps.setObject(8, adminid);ps.executeUpdate();} finally {JDBCUtil.close(connection, ps);}return true;}
5.查询所需的学生信息
public Student findstudent(String id) throws SQLException {PreparedStatement ps = null;Connection connection = null;Student student = new Student();try {connection = JDBCUtil.GetConnection();ps = connection.prepareStatement("SELECT\n" +"id,\n" +"num,\n" +"NAME,\n" +"gender,\n" +"birthday,\n" +"phone,\n" +"address,\n" +"majorid\n" +"FROM student WHERE id = ?");ps.setObject(1, id);ResultSet rs = ps.executeQuery();while (rs.next()) {student.setId(rs.getInt("id"));student.setNum(rs.getInt("num"));student.setName(rs.getString("name"));student.setGender(rs.getString("gender"));student.setBirthday(rs.getDate("birthday"));student.setPhone(rs.getString("phone"));student.setAddress(rs.getString("address"));student.setMajorid(rs.getInt("majorid"));}} finally {JDBCUtil.close(connection, ps);}return student;}
6.修改学生
public void updateStudent(String id, String name, String gender, String birthday, String phone, String address, String majorid, int adminid) throws SQLException {System.out.println("insertstudent");PreparedStatement ps = null;Connection connection = null;try {connection = JDBCUtil.GetConnection();ps = connection.prepareStatement("UPDATE student set NAME=?,gender=?,birthday=?,phone=?,address=?,majorid=?,adminid=?,oper_time=NOW() WHERE id=?\n");ps.setObject(1, name);ps.setObject(2, gender);ps.setObject(3, birthday);ps.setObject(4, phone);ps.setObject(5, address);ps.setObject(6, majorid);ps.setObject(7, adminid);ps.setObject(8, id);ps.executeUpdate();} finally {JDBCUtil.close(connection, ps);}}