本文章基于:前后端分离项目之登录页面(前后端请求、响应和连接数据库)_小俱的一步步的博客-CSDN博客
目录
一、编辑者操作步骤
二、代码实现步骤
以下以存储学生信息为例
一、编辑者操作步骤
1.在前端“编辑”按钮,点击时弹出弹框,出现一个填有该行学生信息的表格。
2.修改当前学生信息,修改时,表格会有提示所填内容规范。修改内容不规范就不会保存。
3.点击保存,关闭编辑弹框,在学生列表中更新已出现的学生信息。
二、代码实现步骤
1.弹出弹框,请求当前行的信息,响应在弹框中的表单中:
前端代码:
由于弹框要在当前显示的组件中打开,需要编辑的组件导入当前组件,作为当前组件的子组件。
import Add from './Add.vue';//添加组件也是当前studentList组件的子组件
import Update from './Update.vue';//导入编辑的组件
export default {
components: { //注册主键
Add,
Update,
},
编辑按钮:
<el-button size="mini" @click="updateStudent(scope.row.id)">编辑</el-button>
对应函数:将编辑组件可视并获取学生信息
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;
}
编辑组件代码:
<template>
<el-dialog title="修改学生信息" :visible.sync="dialogFormVisible">
<el-form :rules="rules" ref="ruleForm" :model="form" label-width="80px">
<el-form-item label="学号" prop="num">
<el-input v-model="form.num"></el-input>
</el-form-item>
<el-form-item label="姓名" prop="name">
<el-input v-model="form.name"></el-input>
</el-form-item>
<el-form-item label="性别">
<el-radio v-model="form.gender" label="男">男</el-radio>
<el-radio v-model="form.gender" label="女">女</el-radio>
</el-form-item>
<el-form-item label="生日">
<el-date-picker value-format="yyyy-MM-dd" v-model="form.birthday" type="date" placeholder="选择日期"
:picker-options="pickerOptions0">
</el-date-picker>
</el-form-item>
<el-form-item label="专业" prop="majorid">
<el-select v-model="form.majorid" placeholder="请选择">
<el-option v-for="item in majorList" :key="item.id" :label="item.name" :value="item.id">
</el-option>
</el-select>
</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>
<el-button type="primary" @click="save('ruleForm')">保存</el-button>
<el-button @click="dialogFormVisible=false">取消</el-button>
</el-form-item>
</el-form>
</el-dialog>
</template>
<script>
export default {
data() {
return {
dialogFormVisible: false,
majorList: [],
form: {
id: "",
num: "",
name: "",
gender: "男",
birthday: "",
phone: "",
address: "",
mark: "save",
majorid: "",
},
rules: {
num: [{
required: true,
message: '请输入学号',
trigger: 'blur',
},
{
min: 1,
max: 15,
message: '长度在 1 到 15 个字符',
trigger: 'blur'
}
],
name: [{
required: true,
message: '请输入姓名',
trigger: 'blur'
},
{
min: 2,
max: 6,
message: '长度在 2 到 6 个字符',
trigger: 'blur'
}
],
majorid: [{
required: true,
message: '请选择专业',
trigger: 'blur'
}],
},
pickerOptions0: {
disabledDate(time) {
return time.getTime() > Date.now() - 8.64e6
}
}
}
},
methods: {
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;
}
});
},
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(); //更新当前列表
}
})
}
});
}
},
mounted() {
this.$http.get("back/student?mark=majorList").then((resp) => {
if (resp.data.code == 200) {
this.majorList = resp.data.data;
}
})
}
}
function jsonToString(jsonobj) {
console.log(jsonobj);
var str = "";
for (var s in jsonobj) {
str += s + "=" + jsonobj[s] + "&";
}
return str.substring(0, str.length - 1);
}
</script>
<style>
</style>
2.双向绑定表单中的数据,将修改后的数据更新在数据库中。
前端代码都在编辑组件中:
保存按钮:
<el-button type="primary" @click="save('ruleForm')">保存</el-button>
保存函数:
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(); //更新当前列表
除此之外,删除和添加功能比编辑简单,可以仿照的写。