Vue项目之用户管理业务模块实践
1、用户分页
本项目所有分页功能都是基于ajax的异步请求来完成的,请求参数是键值对形式 后台响应数据格式使用json数据格式。
请求参数包括页码、每页显示记录数、查询条件。
请求参数的键值对格式为:currentPage:1,pageSize:10,username:''adm''
后台响应数据包括总记录数、当前页、每页显示条数、需要展示的数据集合。
响应数据的json格式为:
{ "currentPage":1 "pageSize":3, "totalCount":8, "totalPage":3, "list":[{用户1},{用户2}..]
}
如下图:
前端页面:
1.1 完善页面
1.1.1 定义分页相关模型数据
tableData: [],//当前页要展示的分页列表数据
search: '',//查询条件
pageSize: 3,//每页显示的记录数
currentPage: 1,//当前页码
totalCount: '',//总记录数
1.1.2 定义分页方法
在页面中提供了findPage方法用于分页查询,为了能够在/user/index.html页面加载后直接可以展示分页数据,可以在VUE提供的钩子函数created中调用findPage方法
实现步骤:
-
初始化请求参数
如果有查询条件,就携带查询条件查询符合条件的当前页数据
-
封装请求参数
当前页、默认每页记录数、查询条件
-
发送axios请求,处理回调
把数据集和总记录数等数据重新赋值给模型
//钩子函数,VUE对象初始化完成后自动执行
created() {
this.findPage();
}
/* 分页查询 */
findByPage() {
//组装参数
var params =new URLSearchParams()
params.append("currentPage",this.currentPage)
params.append("pageSize",this.pageSize)
params.append("name",this.search)
axios.post("http://localhost/education/user?method=findByPage",params).then(resp=>{
//赋值
this.tableData=resp.data.list
this.currentPage=resp.data.currentPage
this.pageSize=resp.data.pageSize
this.totalCount=resp.data.totalCount
this.totalPage=resp.data.totalPage
})
},
1.1.3 完善分页方法执行时机
除了在created钩子函数中调用findPage方法查询分页数据之外,当用户输入完查询条件后分也需要调用findPage方法重新发起查询请求。
为查询按钮绑定离开焦点事件,调用findPage方法
<el-table-column align="left" width="200px">
<template slot="header" slot-scope="scope">
<el-input v-model="search" size="mini" @blur="handleUserList" placeholder="输入用户名称搜索" />
</template>
</el-table-column>
为分页条组件绑定current-change事件,此事件是分页条组件自己定义的事件,当页码改变时触发,对应的处理函数为handleCurrentChange
<el-pagination @size-change="handleSizeChange" :slot="tableData"
@current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[3, 4, 5, 6]"
:page-size="pageSize" layout="total, sizes, prev, pager, next, jumper, slot"
:total="totalCount">
</el-pagination>
定义handleCurrentChange方法
handleCurrentChange: function (currentPage) {
this.currentPage = currentPage;
this.handleUserList();
},
定义handleSizeChange方法
handleSizeChange: function (size) {
this.pageSize = size;
this.handleUserList();
},
1.2 后台代码
1.2.1 servlet
修改education工程,在UserServlet中增加分页查询方法
public void findByPage(HttpServletRequest request, HttpServletResponse response) {
//接受请求参数
String currentPage = request.getParameter("currentPage");
String pageSize = request.getParameter("pageSize");
String name = request.getParameter("name");
//调用业务
PageBean<User> pb =service.findByPage(currentPage,pageSize,name);
//响应数据
JsonUtils.objToJson(pb,response);
}
1.2.2 service类
修改com.ujiuye.service,在UserService实现类中扩展分页查询方法
public PageBean<User> findByPage(String currentPage, String pageSize, String name) {
PageBean<User> pb = new PageBean<>();
int cpage = Integer.parseInt(currentPage);
int size = Integer.parseInt(pageSize);
pb.setCurrentPage(cpage);
pb.setPageSize(size);
//初始化sql
StringBuilder sb = new StringBuilder("select * from user where 1=1 ");
//创建集合来存储?占位符参数
ArrayList<Object> list = new ArrayList<>();
if (name!=null && !name.trim().equals("")) {
//输入了name进行搜索
sb.append(" and name like ? ");
list.add("%" + name + "%");
}
//查询符合条件的总记录数
int totalCount = dao.getListEntity(sb.toString(), User.class, list.toArray()).size();
pb.setTotalCount(totalCount);
//总页数
int totalPage =totalCount%size==0?totalCount/size:totalCount/size+1;
pb.setTotalPage(totalPage);
//分页查询符合条件的数据
sb.append(" limit ?,? ");
list.add((cpage - 1) * size);
list.add(size);
List<User> userList = dao.getListEntity(sb.toString(), User.class, list.toArray());
pb.setList(userList);
return pb;
}
2. 新增用户
2.1 前端页面实现
用户管理页面对应的是/user/index.html页面,根据产品设计的原型已经完成了页面基本结构的编写,现在需要完善页面动态效果。
2.1.1 弹出新增窗口
页面中已经提供了新增页面,当用户在/user/index.html中点击新增用户按钮会打开新增页面。新增页面中的表单在div中由inputVisible属性控制为true显示状态。当点击el-tag标签页关闭的时候设置inputVisible为false会隐藏表单返回到/user/index.html
data: {
ruleForm: {
username: '',
password: '',
name: '',
phone: '',
status: '',
role: '',
age: '',
sex: ''
},
rules: {
username: [
{ required: true, message: '请输入用户名称', trigger: 'blur' },
{ min: 3, max: 11, message: '长度在 3 到 5 个字符', trigger: 'blur' }
],
role: [
{ required: true, message: '请选择角色', trigger: 'change' }
],
name: [
{ required: true, message: '请输入真实姓名', trigger: 'blur' }
],
phone: [
{
required: true,
message: '请输入手机号码',
trigger: 'blur'
},
{
validator: function (rule, value, callback) {
if (/^1[34578]\d{9}$/.test(value) == false) {
callback(new Error("请输入正确的手机号"));
} else {
callback();
}
}, trigger: 'blur'
}
],
password: [
{
required: true,
message: '请输入密码',
trigger: 'blur'
}, {
min: 6,
max: 30,
message: '长度在 6 到 30 个字符'
}, {
pattern: /^(\w){6,20}$/,
message: '只能输入6-20个字母、数字、下划线'
}
],
status: [
{ required: true, message: '请选择状态', trigger: 'change' }
],
sex: [
{ required: true, message: '请选择性別', trigger: 'change' }
],
age: [
{ required: true, message: '年龄不能为空', trigger: 'blur' },
{
validator: function (rule, value, callback) {
if (!Number.isInteger(value)) {
callback(new Error('请输入数字值'));
} else {
if (value < 18) {
callback(new Error('必须年满18岁'));
} else {
callback();
}
}
}, trigger: 'blur'
}
]
},
/*选项卡*/
inputVisible: true,
disable: true,
},
methods: {
/*选项卡关闭 、表单取消*/
handleClose() {
// this.disable = true
this.inputVisible = false
history.go(-1);
},
/* 重置数据 */
resetForm(formName) {
this.$refs[formName].resetFields();
}
}
2.1.2 提交表单数据
点击新增窗口中的确定按钮时,触发submitForm方法,所以需要在submitForm方法中进行完善。
实现步骤:
步骤:
-
校验表单输入项是否合法
-
表单数据校验通过,发送ajax请求将表单数据提交到后台
1.判断后台返回的code值, 200表示添加操作成功, 500为添加操作失败
2.保存成功, 弹出成功提示, 显示服务返回的消息
3.保存失败, 弹出错误提示, 显示服务返回的消息
4.无论什么情况,都重新请求当前分页, 跳转到展示用户页面
-
表单验证失败,弹出验证失败提示
/* 添加用户 */
submitForm(formName) {
this.$refs[formName].validate((valid)=>{
if(valid){
//组装数据发送ajax请求
var params= new URLSearchParams()
params.append("username",this.ruleForm.username)
params.append("password",this.ruleForm.password)
params.append("name",this.ruleForm.name)
params.append("phone",this.ruleForm.phone)
params.append("status",this.ruleForm.status)
params.append("role",this.ruleForm.role)
params.append("age",this.ruleForm.age)
params.append("sex",this.ruleForm.sex)
//发送请求
axios({
url:"http://localhost/education/user?method=insertUser",
data:params,
method:"post"
}).then(resp=>{
if(resp.data.code==200){
//给出成功提示
this.$message.success(resp.data.message)
//跳转到/user/index.html
setTimeout("location.href='http://127.0.0.1:5500/edu/html/User/index.html'",1000)
}else{
this.$message.warning(resp.data.message)
}
})
}else{
//给出提示
this.$message.warning(`表单校验失败`)
}
})
},
2.2 后端业务实现
-
实现步骤:
1、实现后端业务控制器
在UserServlet控制器,提供新增用户的方法,让其调用服务完成新增业务;
2、完善业务实现与业务实现
-
在UserService实现类中实现业务方法
-
在UserDao接口中提供操作数据库方法
最终验证测试,是否插入数据成功
2.2.1 servlet
修改education工程,在UserServlet中增加新增用户方法
public void insertUser(HttpServletRequest request, HttpServletResponse response) throws InvocationTargetException, IllegalAccessException {
//获取数据到Map中
Map<String, String[]> map = request.getParameterMap();
//创建对象
User user = new User();
BeanUtils.populate(user,map);
//调用业务
int row =service.addUser(user);
//响应处理结果
if (row > 0) {
vo = new ResultVo(200, "新增用户成功", null);
} else {
vo = new ResultVo(500, "新增用户失败", null);
}
JsonUtils.objToJson(vo,response);
}
2.2.2 service类
修改com.ujiuye.service,在UserService实现类中扩展方法实现
public int addUser(User u) {
String sql = "insert into user values(null,?,?,?,?,?,?,?,?,?,?)";
return dao.update(sql, u.getName(), u.getPhone(), u.getAge(), u.getSex(), u.getUsername(), u.getPassword(), u.getStatus(), new Date(), u.getRole(), u.getPicture());
}
3. 批量删除用户
3.1 完善页面
为了防止用户误操作,点击删除按钮时需要弹出确认删除的提示,用户点击取消则不做任何操作,用户点击确定按钮再提交删除请求。
3.1.1 全选全不选功能实现
当点击页面中表头上的复选框后、当前页面中所有的复选框将会选中并收集选中行的用户uid放入数组中、反之则不选中
//将选中所有行存入数组
handleSelectionChange(val) {
this.multipleSelection = val;
}
3.1.2 绑定单击事件
需要为删除选中按钮绑定单击事件,并且所选行数据作为参数传递给处理函数
<el-button type="warning" @click="delAll()">删除选中</el-button>
用户点击删除按钮会执行delAll方法,此处需要完善delAll方法,弹出确认提示信息。ElementUI提供了$confirm方法来实现确认提示信息弹框效果
3.1.3 发送请求
如果用户点击确定按钮就需要发送ajax请求,并且将当前检查项的id作为参数提交到后台进行删除操作
实现步骤:
-
提示是否删除
-
确认删除,发送axios请求,进行回调处理
-
删除成功,弹出消息, 提示服务器返回的正常消息,刷新当前页面
-
删除失败,弹出消息, 提示服务器返回的错误消息
-
/* 批量删除 */
delAll() {
/*
multipleSelection:所有被选中的复选框
*/
for(var i=0;i<this.multipleSelection.length;i++){
//向数组中添加要删除的uid
this.delarr.push(this.multipleSelection[i].uid)
}
var params =new URLSearchParams()
params.append("ids",this.delarr)
//发送请求
axios({
url:"http://localhost/education/user?method=delAll",
data:params,
method:"post"
}).then(resp=>{
if(resp.data.code==200){
//给出提示
this.$message.success(resp.data.message)
//调用方法查询获取最新数据
this.currentPage=1
this.findByPage()
}else{
this.$message.warning(resp.data.message)
}
})
},
3.2 后台代码
3.2.1 servlet
修改education工程,在UserServlet中增加批量删除用户方法
public void delAll(HttpServletRequest request, HttpServletResponse response){
//获取参数
String ids = request.getParameter("ids");
//调用业务
int row =service.delAll(ids);
//响应处理结果
if (row > 0) {
vo = new ResultVo(200, "批量删除用户成功", null);
} else {
vo = new ResultVo(500, "批量删除用户失败", null);
}
JsonUtils.objToJson(vo,response);
}
3.2.3 service类
修改com.ujiuye.service,在UserService实现类中扩展方法实现
public int delAll(String ids) {
String sql = "delete from user where uid in(" + ids + ")";
return dao.update(sql);
}
4. 编辑用户
4.1 完善页面
用户点击编辑按钮时,需要弹出编辑窗口并且将当前记录的数据进行回显,用户修改完成后点击确定按钮将修改后的数据提交到后台进行数据库操作。
4.1.1 绑定单击编辑按钮事件
需要为编辑按钮绑定单击事件,并且将当前行数据作为参数传递给处理函数
<el-button size="mini" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
/* 修改回显用户信息 */
handleEdit(index, row) {
//打开对话框
this.dialogVisible = true
//将当前行数据赋值到ruleForm数组
this.ruleForm = row;
}
4.1.2 发送请求
在编辑窗口中修改完成后,点击确定按钮提交请求,所以需要为确定按钮绑定事件并提供处理函数submitForm
实现步骤:
-
进行表单验证
-
表单验证成功,发送axios请求,进行回调处理
2.编辑成功,弹出成功提示,显示服务返回的消息
3.编辑失败,弹出错误提示,显示服务返回的消息
4.无论执行结果如何,隐藏编辑窗口, 重新发送请求查询分页数据
-
表单验证失败, 弹出验证失败提示
<el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
/* 修改提交 */
submitForm(formName) {
this.$refs[formName].validate((valid)=>{
if(valid){
var params =new URLSearchParams()
//组装请求参数
params.append("username",this.ruleForm.username)
params.append("password",this.ruleForm.password)
params.append("name",this.ruleForm.name)
params.append("phone",this.ruleForm.phone)
params.append("status",this.ruleForm.status)
params.append("role",this.ruleForm.role)
params.append("age",this.ruleForm.age)
params.append("sex",this.ruleForm.sex)
params.append("uid",this.ruleForm.uid)
//发送请求
axios.post("http://localhost/education/user?method=updateUser",params).then(resp=>{
if(resp.data.code==200){
//提示
this.$message.success(resp.data.message)
this.currentPage=1
this.findByPage()
//关闭对话框
this.dialogVisible=false
}else{
//提示
this.$message.warning(resp.data.message)
}
})
}else{
this.$message.warning(`表单校验失败`)
}
})
},
4.2 后台代码
4.2.1 servlet
修改education工程,在UserServlet中增加更新用户方法
public void updateUser(HttpServletRequest request, HttpServletResponse response) throws InvocationTargetException, IllegalAccessException {
//接受参数到Map中
Map<String, String[]> map = request.getParameterMap();
//创建实体类
User user = new User();
BeanUtils.populate(user,map);
//调用业务
int row =service.updateUser(user);
//响应处理结果
if (row>0) {
vo = new ResultVo(200, "修改用户信息成功", null);
}else{
vo = new ResultVo(500, "修改用户信息失败", null);
}
JsonUtils.objToJson(vo,response);
}
4.2.3 service类
修改com.ujiuye.service.impl,在UserServiceImpl实现类中扩展方法实现
public int updateUser(User u) {
String sql = "update user set name =?,phone=?,age=?,sex=?,username=?,password=?,status=?,createtime=?,role=?,picture=? where uid =?";
return dao.update(sql,u.getName(), u.getPhone(), u.getAge(), u.getSex(), u.getUsername(), u.getPassword(), u.getStatus(), new Date(), u.getRole(), u.getPicture(),u.getUid());
}
5.详情用户
5.1 完善页面
用户点击详情按钮时,需要弹出详情窗口并且将当前记录的数据赋值给ruleForm数组进行回显
5.1.1 绑定单击详情按钮事件
需要为编辑按钮绑定单击事件,并且将当前行数据作为参数传递给处理函数
<el-button size="mini" type="danger" @click="handlelook(scope.$index, scope.row)">详情</el-button>
/* 详情 */
handlelook(index, row) {
//打开对话框
this.dialogVisible1 = true
//将当前行数据赋值给ruleForm数组
this.ruleForm = row;
}
- 点赞
- 收藏
- 关注作者
评论(0)