前后端分离项目之修改存储信息

本文章基于:前后端分离项目之登录页面(前后端请求、响应和连接数据库)_小俱的一步步的博客-CSDN博客 

目录

一、编辑者操作步骤

二、代码实现步骤


 

以下以存储学生信息为例

一、编辑者操作步骤

1.在前端“编辑”按钮,点击时弹出弹框,出现一个填有该行学生信息的表格。

前后端分离项目之修改存储信息_第1张图片

 

2.修改当前学生信息,修改时,表格会有提示所填内容规范。修改内容不规范就不会保存。

前后端分离项目之修改存储信息_第2张图片

3.点击保存,关闭编辑弹框,在学生列表中更新已出现的学生信息。 

二、代码实现步骤

1.弹出弹框,请求当前行的信息,响应在弹框中的表单中:

前端代码:

        由于弹框要在当前显示的组件中打开,需要编辑的组件导入当前组件,作为当前组件的子组件。

	import Add from './Add.vue';//添加组件也是当前studentList组件的子组件
	import Update from './Update.vue';//导入编辑的组件
	export default {
		components: { //注册主键
			Add,
			Update,
		},

         编辑按钮:

编辑

         对应函数:将编辑组件可视并获取学生信息

updateStudent(id){
		this.$refs.update.dialogFormVisible = true;//将编辑组件可视
		this.$refs.update.getStudent(id);//获取学生信息				
}

         获取学生信息前端代码:

            getStudent(id) {
				this.$http.get("back/student?mark=getStudent&id=" + id).then((resp) => {
					if (resp.data.code == 200) {
						this.form.id = resp.data.data.id;
						this.form.num = resp.data.data.num;
						this.form.name = resp.data.data.name;
						this.form.gender = resp.data.data.gender;
						this.form.birthday = resp.data.data.birthday;
						this.form.phone = resp.data.data.phone;
						this.form.address = resp.data.data.address;
						this.form.majorid = resp.data.data.majorId;
					}
				});
			},

 后端代码:

    private void getStudentById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        PrintWriter printWriter = resp.getWriter();
        CommonResult commonResult = null;
        try{
            String id= req.getParameter("id");
            StudentDao studentDao = new StudentDao();
            Student student =  studentDao.getStudentById(id);
            commonResult = new CommonResult(200,student,"成功");
        }catch (Exception e){
            e.printStackTrace();
            commonResult = new CommonResult(500,"系统忙");
        }
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(commonResult);
        printWriter.print(json);
    }

         StudentDao中从数据库中获取学习信息的方法:

 public Student getStudentById(String id) throws SQLException, ClassNotFoundException {
        Connection connection = null;
        PreparedStatement ps = null;
        Student student = new Student();
        try {
            connection = JDBCUtil.connestionJDBC();

            ps = connection.prepareStatement("SELECT\n" +
                    "  id,\n" +
                    "  num,\n" +
                    "  NAME,\n" +
                    "  gender,\n" +
                    "  birthday,\n" +
                    "  majorid,\n" +
                    "  phone,\n" +
                    "  address\n" +
                    "FROM\n" +
                    "  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.setPhone(rs.getString("phone"));
                student.setBirthday(rs.getDate("birthday"));
                student.setMajorId(rs.getInt("majorid"));
                student.setAddress(rs.getString("address"));
            }
        } finally {
            JDBCUtil.close(connection,ps);
        }
        return student;
    }

 编辑组件代码:





2.双向绑定表单中的数据,将修改后的数据更新在数据库中。

 前端代码都在编辑组件中:

        保存按钮:

保存

        保存函数:

			save(formName) {

				this.$refs[formName].validate((valid) => {
					if (valid) {
						this.$http.post("back/student", jsonToString(this.form)).then((resp) => {
							if (resp.data.code == 200) {

								this.$message({
									message: resp.data.message,
									type: 'success'
								});

								this.dialogFormVisible = false; //关闭窗口
								this.$router.go(); //更新当前列表
							}
						})
					}
				});

			}

后端保存代码:由于在新增学生信息时也使用了改方法,编辑方法时将学生的id作为标识,因此下面判断了是否id为空,若不为空,将调用数据库修改的方法。

private void saveStudent(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        PrintWriter printWriter = resp.getWriter();
        CommonResult commonResult = null;
        try {
            String id = req.getParameter("id");
            String num = req.getParameter("num");
            String name = req.getParameter("name");
            String gender = req.getParameter("gender");
            String birthday = req.getParameter("birthday");
            String majorid = req.getParameter("majorid");
            String phone = req.getParameter("phone");
            String address = req.getParameter("address");

            //需要从taken中获取当前登录人的id
            //获取请求头中的token
            String token = req.getHeader("adminToken");
            //解析token
            DecodedJWT tokenInfo = JWTUtil.getTokenInfo(token);
            //获取到token中管理员id
            Integer adminId = tokenInfo.getClaim("id").asInt();

            StudentDao studentDao = new StudentDao();

            if (id==null){
                studentDao.saveStudent(num,name,gender,birthday,majorid,phone,adminId,address);
            }else {
                studentDao.updateStudent(id,num,name,gender,birthday,majorid,phone,adminId,address);
            }

            commonResult = new CommonResult(200,null,"保存成功");
        }catch (Exception e){
            e.printStackTrace();
            commonResult = new CommonResult(500,"系统忙");
        }
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(commonResult);
        printWriter.print(json);
    }

 数据库修改信息方法:

    public void updateStudent(String id, String num, String name, String gender,
                              String birthday, String majorid, String phone, Integer adminId, String address) throws ClassNotFoundException, SQLException {
        Connection connection = null;
        PreparedStatement ps = null;
        try {
            connection = JDBCUtil.connestionJDBC();
            ps = connection.prepareStatement("UPDATE student SET num=?,NAME=?,gender=?,birthday=?,majorid=?,phone=?,address=?,adminid=?,oper_time=? WHERE id=?");
            ps.setObject(1, num);
            ps.setObject(2, name);
            ps.setObject(3, gender);
            ps.setObject(4, birthday);
            ps.setObject(5, majorid);
            ps.setObject(6, phone);
            ps.setObject(7, address);
            ps.setObject(8, adminId);
            ps.setObject(9, new Date());
            ps.setObject(10, id);
            ps.executeUpdate();
        } finally {
            JDBCUtil.close(connection,ps);
        }
    }

后端连接数据库的方法已经封装在JDBCUtil类中:

//封装jdbc
public class JDBCUtil {

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");//初始化驱动程序
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    public static Connection connestionJDBC() throws SQLException {
        String url = "jdbc:mysql://127.0.0.1:3306/web_db?serverTimezone=Asia/Shanghai";
        String uname = "root";
        String pwd = "123456";
        Connection connection = DriverManager.getConnection(url, uname, pwd);
        return connection;
    }
    public static void close(Connection connection,PreparedStatement ps) throws SQLException {
        if (connection != null) {
            connection.close();
        }
        if (ps != null) {
            ps.close();
        }
    }
}

3.刷新学生列表,将修改后的数据更新显示在前端。

 this.dialogFormVisible = false; //关闭窗口
 this.$router.go(); //更新当前列表

除此之外,删除和添加功能比编辑简单,可以仿照的写。

你可能感兴趣的:(前端,servlet,vue.js,elementui,java)