1.ElementUI整合SpringBoot前后端分离实现用户增删改查
效果展示
2.前端核心代码
项目目录
main.js引入
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import router from './router'
import axios from 'axios'
Vue.prototype.$http = axios
Vue.config.productionTip = false
Vue.use(ElementUI);
App.vue
<template>
<div id="app">
<el-container>
<el-header>
<!--导航菜单-->
<el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" @select="handleSelect">
<el-menu-item index="/index">主页</el-menu-item></el-menu-item>
<el-menu-item index="/userslist">用户管理</el-menu-item></el-menu-item></el-menu-item>
<el-menu-item index="/mags">消息中心</el-menu-item>
<el-menu-item index="/orders">订单管理</el-menu-item>
</el-menu>
</el-header>
<el-main>
<!-- 路由组件 -->
<router-view/>
</el-main>
</el-container>
</div>
</template>
<script>
export default {
name: 'App',
data() {
return {
activeIndex: this.$route.path,//获取当前路由路径,解决刷新网页报错问题
};
},
methods: {
handleSelect(key, keyPath) {
console.log(key, keyPath);
// 切换路由
this.$router.push(key);
}
}
}
</script>
<style></style>
路由router目录下index.js
import Vue from 'vue'
import Router from 'vue-router'
import Index from '../components/Index'
import List from '../components/user/List'
Vue.use(Router)
export default new Router({
routes: [
{
path:'/',//配置根路由
component:Index
},
{
path: '/index',
component: Index
},
{
path:'/userslist',
component:List
}
]
})
用户管理页面List.vue(前端核心增删改查业务)
<template lang="">
<div>
<el-table
:data="tableData.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
border
:height="300"
style="width: 100%">
<el-table-column
fixed
prop="id"
label="编号"
width="150">
</el-table-column>
<el-table-column
prop="name"
label="姓名"
width="120">
</el-table-column>
<el-table-column
prop="birth"
label="生日"
width="120">
</el-table-column>
<el-table-column
prop="address"
label="地址"
width="300">
</el-table-column>
<el-table-column
prop="sex"
label="性别"
width="120">
</el-table-column>
<el-table-column
fixed="right"
width="200">
<template slot="header" slot-scope="scope">
<el-input
v-model="search"
size="mini"
placeholder="输入关键字搜索"/>
</template>
<template slot-scope="scope">
<el-button
size="mini"
@click="editUser(scope.$index, scope.row)">编辑</el-button>
<el-popconfirm
confirm-button-text='好的'
cancel-button-text='不用了'
icon="el-icon-info"
icon-color="red"
title="确定删除吗?"
@confirm="handleDelete(scope.$index, scope.row)"
>
<el-button
size="mini"
type="danger"
slot="reference">删除</el-button>
</el-popconfirm>
</template>
</el-table-column>
</el-table>
<!-- 表格分页导航开始 -->
<el-row>
<el-col :span="8" :offset="6">
<el-pagination style="margin: 10px 0px;"
prev-text="上一页"
next-text="下一页"
layout="prev, pager, next , jumper , total , sizes"
background
:page-size="size"
:current-page="pageNow"
:page-sizes="[2,4,8,12,16,20]"
@current-change="findPage"
@size-change="findSize"
:total="totals">
</el-pagination>
</el-col>
</el-row>
<!-- 表格分页导航结束 -->
<el-button style="margin-top: 10px;" type="success" size="mini" @click="show = !show">添加</el-button>
<!-- 添加表单开始 -->
<transition name="el-fade-in-linear">
<div v-show="show" class="transition-box">
<el-form ref="form" :model="form" label-width="80px" label-suffix=":">
<el-form-item label="姓名">
<el-input v-model="form.name"></el-input>
</el-form-item>
</el-form-item>
<el-form-item label="生日">
<el-date-picker value-format="yyyy-MM-dd" type="date" placeholder="选择日期" v-model="form.birth" style="width: 100%;"></el-date-picker>
</el-form-item>
<el-form-item label="性别">
<el-radio-group v-model="form.sex">
<el-radio label="男"></el-radio>
<el-radio label="女"></el-radio>
</el-radio-group>
</el-form-item>
<el-form-item label="地址">
<el-input type="textarea" v-model="form.address"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="onSubmit">保存信息</el-button></el-button>
<el-button @click="show = false">取消</el-button>
</el-form-item>
</el-form>
</div>
</transition>
<!-- 添加表单结束 -->
<!-- 对话框开始 -->
<el-dialog title="修改用户信息" :visible.sync="dialogFormVisible">
<el-form :hide-required-asterisk="false" :rules="rules" ref="userForm" :model="form" label-width="80px" label-suffix=":">
<el-form-item label="姓名" prop="name">
<el-input v-model="form.name"></el-input>
</el-form-item>
</el-form-item>
<el-form-item label="生日" prop="birth">
<el-date-picker type="date" placeholder="选择日期" v-model="form.birth" style="width: 100%;"></el-date-picker>
</el-form-item>
<el-form-item label="性别">
<el-radio-group v-model="form.sex">
<el-radio label="男"></el-radio>
<el-radio label="女"></el-radio>
</el-radio-group>
</el-form-item>
<el-form-item label="地址" prop="address">
<el-input type="textarea" v-model="form.address"></el-input>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="dialogFormVisible = false">取 消</el-button>
<el-button type="primary" @click="update('userForm')">确 定</el-button>
</div>
</el-dialog>
<!-- 对话框结束 -->
</div>
</template>
<script>
export default {
methods: {
findSize(size){//用来处理每页显示记录发生变化的方法
this.size = size
this.findAllTableData(this.page,size)
},
findPage(page){//用来处理分页相关方法
this.page=page
this.findAllTableData(page,this.size)
},
editUser(index,row){
this.dialogFormVisible=true
this.$http("http://localhost:8989/user/findUserById?id="+row.id).then(res=>{
this.form = res.data;
})
},
update(userForm){
//添加表单验证
this.$refs[userForm].validate((valid) => {
if (valid) {
//验证通过发送更新请求
//发送一个axios请求
this.$http.post("http://localhost:8989/user/saveUserById",this.form).then(res=>{
if(res.data.status){
this.$message({
message: res.data.msg,
type: 'success'
});
//关闭对话框
this.dialogFormVisible=false
//添加成功以后还要清空表单信息
this.form={}
//调用查询数据方法,重新渲染数据
this.findAllTableData();
}else{
this.$message.error(res.data.msg);
}
})
} else {
this.$message.error("用户数据不合法");
return false;
}
});
},
handleDelete(index, row) {
console.log(index, row);
//发送删除接口
this.$http.get("http://localhost:8989/user/deleteUserById?id="+row.id).then(res=>{
if(res.status){
this.$message({
message: res.data.msg,
type: 'success'
});
//刷新表格数据
this.findAllTableData();
}else{
this.$message.error(res.data.msg);
}
})
},
onSubmit() {
console.log('submit!');
//发送一个axios请求
this.$http.post("http://localhost:8989/user/save",this.form).then(res=>{
if(res.data.status){
this.$message({
message: '恭喜你,'+res.data.msg,
type: 'success'
});
//添加成功以后还要清空表单信息
this.form={}
//隐藏表单
this.show=false
//调用查询数据方法,重新渲染数据
this.findAllTableData();
}else{
this.$message.error(res.data.msg);
}
})
},
findAllTableData(page,size){
//处理page参数初始化问题
page = page?page:this.pageNow;
size = size?size:this.size;
this.$http.get("http://localhost:8989/user/findByPage?pageNow="+page+"&pageSize="+size).then(res=>{
//回调中获取响应结果
console.log(res)
this.tableData = res.data.users;
this.totals = res.data.total;
})
}
},
data() {
return {
tableData: [],
search: '',
show: true,
form: {
id:'',
name: '',
birth:'',
sex:'男',
address:''
},
dialogFormVisible: false,
rules: {
name: [
{ required: true, message: '请输入用户姓名!', trigger: 'blur' }
],
birth: [
{ required: true, message: '请输入用户出生年月!', trigger: 'blur' }
],
address: [
{ required: true, message: '请输入用户地址!', trigger: 'blur' }
],
},
//分页相关参数
totals:0,
size:4,
pageNow:1
}
},
created() {
this.findAllTableData();
},
}
</script>
<style lang="">
.transition-box {
margin-bottom: 10px;
width: 100%;
height: 600px;
border-radius: 4px;
color: #fff;
padding: 40px 20px;
box-sizing: border-box;
margin-right: 20px;
}
</style>
3.后端核心代码
项目架构如下
数据库sql
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for t_users
-- ----------------------------
DROP TABLE IF EXISTS `t_users`;
CREATE TABLE `t_users` (
`id` int(0) NOT NULL AUTO_INCREMENT,
`name` varchar(80) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`birth` timestamp(0) NULL DEFAULT NULL,
`sex` varchar(4) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`address` varchar(120) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 13 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of t_users
-- ----------------------------
INSERT INTO `t_users` VALUES (1, 'b0', '2023-01-02 08:00:00', '男', '成都');
INSERT INTO `t_users` VALUES (2, 'kuku', '2023-01-01 22:59:08', '男', '四川');
INSERT INTO `t_users` VALUES (3, 'b0', '2023-01-09 08:00:00', '男', '自贡');
INSERT INTO `t_users` VALUES (9, 'kuku', '2023-01-10 08:00:00', '男', 'hello');
INSERT INTO `t_users` VALUES (10, 'sadas', '2023-01-09 08:00:00', '女', 'asdasd');
INSERT INTO `t_users` VALUES (11, 'asdasd', '2023-01-29 08:00:00', '女', 'asdasd');
INSERT INTO `t_users` VALUES (12, 'asdasd', '2023-01-12 08:00:00', '女', 'asdasd');
INSERT INTO `t_users` VALUES (13, '12321', '2023-01-27 08:00:00', '男', '1231231');
INSERT INTO `t_users` VALUES (14, '123123', '2023-01-24 08:00:00', '男', '123123');
SET FOREIGN_KEY_CHECKS = 1;
配置文件
server:
port: 8989
spring:
application:
name: elementusers
devtools:
remote:
context-path: /
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/elementusers?characterEncoding=UTF-8
username: root
password: 123456
web:
resources:
static-locations: classpath:/static/
mybatis:
mapper-locations: classpath:com/b0/mapper/*.xml
type-aliases-package: com.b0.elementusers.entity
configuration:
map-underscore-to-camel-case: true
后端使用springboot+mybatis 结合Lombok快速开发接口
实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Accessors(chain = true)
public class User {
private Integer id;
private String name;
//导包导import java.util.Date;
@JsonFormat(pattern = "yyyy-MM-dd")
private Date birth;
private String sex;
private String address;
}
vo返回值拓展类
@Data
public class Result {
private Boolean status=true;
private String msg;
}
mybatis数据库操作接口
@Mapper
public interface UserDAO {
//查询所有用户信息
List<User> findAll();
//保存用户信息
void saveUser(User user);
//根据id删除用户信息
void deleteUserById(@Param("id") Integer id);
//根据id查询用户
User findUserById(@Param("id") Integer id);
//根据用户id修改用户信息
void updateUserById(User user);
//分页查询
List<User> findByPage(@Param("start") Integer start,@Param("rows") Integer rows);
// 查询总条数
Long findTotals();
}
mybatis配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace="com.b0.mybatis.mapper.UserMapper" -->
<mapper namespace="com.b0.elementusers.dao.UserDAO">
<!-- 查询所有的方法:List<User> findAll();-->
<select id="findAll" resultType="User">
select id,name,birth,sex,address
from t_users
</select>
<!-- 保存用户:void saveUser(User user);useGeneratedKeys配置自增长key-->
<insert id="saveUser" parameterType="User" useGeneratedKeys="true" keyProperty="id">
insert into t_users values(#{id},#{name},#{birth},#{sex},#{address})
</insert>
<!-- 根据id删除用户信息:void deleteUserById(Integer id);-->
<delete id="deleteUserById" parameterType="Integer">
delete from t_users where id = #{id}
</delete>
<!-- 根据id查看用户信息:void findUserById(Integer id); -->
<select id="findUserById" resultType="User">
select id,name,birth,sex,address
from t_users where id = #{id}
</select>
<!-- 根据用户id修改用户:void updateUserById(User user);-->
<update id="updateUserById" parameterType="User">
update t_users
set name=#{name},birth=#{birth},sex=#{sex},address=#{address}
where id=#{id}
</update>
<!-- 分页查询List<User> findByPage(@Param("start") Integer start,@Param("rows") Integer rows);-->
<select id="findByPage" resultType="User">
select id,name,birth,sex,address
from t_users limit #{start},#{rows}
</select>
<!-- 查询总条数Long findTotals();-->
<select id="findTotals" resultType="Long">
select count(id) from t_users
</select>
</mapper>
service接口
public interface UserService {
//查询所有方法
List<User> findAll();
//保存用户信息
void saveUser(User user);
//根据id删除用户信息
void deleteUserById(Integer id);
//根据id查询用户
User findUserById(@Param("id") Integer id);
//根据用户id修改用户信息
void updateUserById(User user);
//分页查询
List<User> findByPage(Integer pageNow, Integer rows);
// 查询总条数
Long findTotals();
}
service实现类
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Autowired
private UserDAO userDAO;
@Override
public List<User> findAll() {
return userDAO.findAll();
}
@Override
public void saveUser(User user) {
userDAO.saveUser(user);
}
@Override
public void deleteUserById(Integer id) {
userDAO.deleteUserById(id);
}
@Override
public User findUserById(Integer id) {
return userDAO.findUserById(id);
}
@Override
public void updateUserById(User user) {
userDAO.updateUserById(user);
}
@Override
public List<User> findByPage(Integer pageNow, Integer rows) {
int start = (pageNow-1)*rows;
List<User> userList = userDAO.findByPage(start, rows);
return userList;
}
@Override
public Long findTotals() {
Long totals = userDAO.findTotals();
return totals;
}
}
controller控制层
@RestController
@CrossOrigin(origins = "*")//全局跨域,解决跨域相关问题
@RequestMapping("user")
public class UserController {
@Autowired
private UserService userService;
//根据id查询用户findUserById
@RequestMapping("findUserById")
public User findUserById(Integer id){
return userService.findUserById(id);
}
//删除用户
@GetMapping("deleteUserById")
public Result deleteUserById(Integer id){
Result result = new Result();
try {
userService.deleteUserById(id);
result.setMsg("删除用户成功!");
}catch (Exception e){
e.printStackTrace();
result.setStatus(false);
result.setMsg("删除用户失败!");
}
return result;
}
//查询所有用户
@GetMapping("findAll")
public List<User> findAll(){
return userService.findAll();
}
//保存用户
@PostMapping("save")
public Result saveUser(@RequestBody User user){
Result result = new Result();
try {
userService.saveUser(user);
result.setMsg("保存用户成功!");
}catch (Exception e){
e.printStackTrace();
result.setStatus(false);
result.setMsg("保存用户失败!");
}
return result;
}
//根据用户id保存用户
@PostMapping("saveUserById")
public Result updateUserById(@RequestBody User user){
Result result = new Result();
try {
userService.updateUserById(user);
result.setMsg("修改用户数据成功!");
}catch (Exception e){
e.printStackTrace();
result.setStatus(false);
result.setMsg("修改用户数据失败!");
}
return result;
}
//分页查询的方法
@GetMapping("findByPage")
public Map<String,Object> findByPage(Integer pageNow,Integer pageSize){
Map<String,Object> result = new HashMap<>();
pageNow = pageNow==null?1:pageNow;
pageSize = pageSize==null?4:pageSize;
List<User> users = userService.findByPage(pageNow, pageSize);
//总条数
Long totals = userService.findTotals();
result.put("users",users);
result.put("total",totals);
return result;
}
}