Vue + Spring Boot project actual combat: personnel management system - (3) recycle bin page and method implementation


foreword

The project is almost finished, and I have been busy studying other things recently, so I haven't had time to write an article, so I will update it today! ! !

The basic idea

  In fact, the realization of the recycle bin is not difficult, it only needs reverse thinking to realize it.
  First create two entity classes. They are RecycleUser and RecycleEmployee respectively. The attributes of the entity class are the same as the previous User class and Employee class, just copy them directly, and then create two new database tables to store the data of recycling information respectively. The core is that when deleting a user on the user management page, the user information to be deleted will be saved in the recycle bin. Although this function seems to be dispensable, it is still quite useful to a certain extent hahahahaha.


Tip: The following is the text of this article, and the following cases are for reference

1. Writing the front-end page

The case here is based on the page recycled by the user, and the method of employee recycling is the same!

1. Write user recycling management vue page

Recycling management page directory structure
insert image description here

vue-layout

<!-- 回收用户信息页面 -->
<template>
  <!-- 主布局 -->
  <div class="container">
    <!-- 卡片式布局 -->
    <el-card>
      <el-row :gutter="25">
        <!--设置间隙  -->
        <!-- 搜索区域 -->
        <el-col :span="10"
          ><!-- 列宽 -->
          <el-input
            placeholder="请输入搜索内容"
            :model="fromData.name"
            clearable
            @cleaer="searchUserList"
          >
            <!-- 搜索功能按钮,用语法糖绑定查询用户的方法 -->
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="searchUserList"
            ></el-button>
          </el-input>
        </el-col>

        <el-col :span="4">
          <!-- 添加用户按钮 -->
          <el-button type="primary" @click="searchUserList">搜索用户</el-button>
        </el-col>
      </el-row>

      <!-- table表单数据-->
      <el-table
        style="
          font-size: 14px;
          box-shadow: 10px 10px 5px rgba(99, 99, 153, 0.2);
        "
        :data="userList"
        border
        stripe
        :header-cell-style="{ background: '#f8f8f9', color: '#515a6e' }"
      >
        <!-- 可勾选控件 -->
        <el-table-column type="selection"></el-table-column>

        <!-- 用户名列 -->
        <el-table-column
          label="用户名"
          prop="username"
          align="center"
          min-width="10%"
        ></el-table-column>

        <!-- 邮箱列 -->
        <el-table-column
          label="邮箱"
          prop="email"
          align="center"
          min-width="10%"
        ></el-table-column>

        <!-- 密码列 -->
        <el-table-column
          label="密码"
          prop="password"
          align="center"
          min-width="10%"
        ></el-table-column>

        <!-- 角色列 -->
        <el-table-column
          label="角色"
          prop="role"
          align="center"
          min-width="10%"
        ></el-table-column>

        <!-- 修改时间列 -->
        <el-table-column
          label="修改时间"
          prop="modifyTime"
          align="center"
          min-width="10%"
        ></el-table-column>

        <!-- 状态列 -->
        <el-table-column
          label="状态"
          prop="state"
          align="center"
          min-width="10%"
        >
          <template slot-scope="scope">
            <el-tag v-model="scope.row.state">{
   
   { scope.row.state }}</el-tag>
          </template>
          <!-- <el-tag type="warning">待回收</el-tag> -->
        </el-table-column>

        <!-- 作用域操作,将操作放在同一个列中 -->
        <el-table-column label="操作" align="center" min-width="15%">
          <template slot-scope="scope">
            <!-- 回收按钮 -->
            <el-tooltip content="回收" placement="top">
              <el-button
                type="success"
                icon="el-icon-upload"
                size="mini"
                @click="handleRestore(scope.$index, scope.row)"
              ></el-button>
            </el-tooltip>

            <!--  修改按钮 -->
            <el-tooltip content="修改" placement="top">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="deleteUser(scope.row.id)"
              ></el-button>
            </el-tooltip>

            <!--  删除按钮 -->
            <el-tooltip content="彻底删除" placement="top">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="handleDelete(scope.row.id, scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- size-change:每页条数 -->
      <div class="block" style="text-align: center; margin-top: 15px">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="fromData.pageIndex"
          :page-sizes="pageInfo.pageSizes"
          :page-size="fromData.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total"
        >
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

js

import {
    
    
  list,
  delUser,
  restore,
} from "@/api/recycle/index"; /* 调用后台api的接口 */
export default {
    
    
  created() {
    
    
    this.queryUserList(); //挂载查询用户方法
    const loading = this.$loading({
    
    
      lock: true,
      text: "数据加载中......",
      spinner: "el-icon-loading",
      background: "rgba(0, 0, 0, 0.7)",
    });
    setTimeout(() => {
    
    
      loading.close();
    }, 1000); /* 设置时间为1秒 */
  },
  //数据定义
  data() {
    
    
    return {
    
    
      userList: [], //查询信息封装实体
      fromData: {
    
    
        name: "",
        pageIndex: 1, //当前页码,为第一页
        pageSize: 5, //默认每页最大数为5,可以动态的切换每页最大数
      },
      pageInfo: {
    
    
        total: 0, //总数,初始值为0
        pageSizes: [1, 5, 10, 20], //定义每次显示最大的条数
      },
    };
  },
  methods: {
    
    
    //查询在回收站用户的方法
    queryUserList() {
    
    
      var $that = this;
      list(this.fromData).then((res) => {
    
    
        if (res.code == 200 && res.success == "success") {
    
    
          $that.userList = res.data.list;
          $that.pageInfo.total = res.data.total;
        }
      });
    },

    //搜索员工方法实现
    searchUserList() {
    
    
      this.queryUserList();
      this.$message({
    
    
        message: "查询成功,结果如下",
        type: "success",
      });
    },

    //回收站功能已实现05.30
    handleRestore(index, row) {
    
    
      var that = this;
      this.$confirm(
        "此操作将还原用户: " + row.username + " , 是否继续?",
        "提示",
        {
    
    
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
    
    
          //定义回收的参数,分别是id,用户名,邮箱,密码,修改时间,状态,角色
          var params = {
    
    
            id: row.id, //用户id
            username: row.username, //用户名
            email: row.email, //用户邮箱
            password: row.password, //用户密码
            modifyTime: row.modifyTime, //用户修改时间
            role: row.role, //用户角色
            state: row.state, //用户状态
          };
          restore(params).then(); /* 在回收的同时,将数据删除 */
          delUser(params).then((res) => {
    
    
            if (res.code == 200 && res.success == "success" && res.data >= 1) {
    
    
              this.$message({
    
    
                type: "success",
                message: "还原" + row.username + "成功!",
              });
              this.queryUserList();
            } else {
    
    
              this.$message({
    
    
                type: "success",
                message: "还原" + row.username + "失败!",
              });
            }
          });
        })
        .catch(() => {
    
    
          //点击取消
          this.$message({
    
    
            type: "info",
            message: "已取消还原",
          });
        });
    },

    //删除功能并恢复已实现05.30
    handleDelete(id, row) {
    
    
      this.$confirm(
        "此操作将永久删除 " + row.username + " , 是否继续?",
        "提示",
        {
    
    
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true, //将位置设置在中心
        }
      ).then(() => {
    
    
        var params = {
    
     id: row.id }; //根据用户id进行删除
        //点击确定
        delUser(params).then((res) => {
    
    
          if (res.code == 200 && res.success == "success" && res.data >= 1) {
    
    
            this.$message({
    
    
              type: "success",
              message: "删除" + row.username + "成功!",
            });
            this.queryUserList(); /* 重新调用查询回收站用户的方法 */
          } else {
    
    
            this.$message({
    
    
              type: "danger",
              message: "删除" + row.username + "失败!",
            });
          }
        });
      });
    },
    //每页显示的条目个数
    handleSizeChange(val) {
    
    
      this.fromData.pageSize = val;
      this.queryUserList(); //获取当前用户列表
    },
    //切换当前页数方法
    handleCurrentChange(val) {
    
    
      this.fromData.pageIndex = val;
      this.queryUserList(); //获取当前用户列表
    },
  },
};
</script>

2. Encapsulate the api interface

The api interface is generally used to call the back-end method to realize the data interaction effect of the front-end and back-end! ! !
Under the api folder, create a new recycle file to encapsulate the api interface method.
PS: When using axois for the first time, npm intsall axios is required. And configure the path of axios in the main.js file, the request timeout time! The specific configuration method can be queried through the document.

import request from '@/util/request.js'
//回收管理api接口

/* 没有配置默认地址的话,则显示在main.js文件中9000端口,用户回收方法定义*/
export function list(params) {
    
    
    return request({
    
    
        url: 'http://127.0.0.1:9007/sys/recycle/list',
        //http://127.0.0.1:9007/api/auth/login
        method: 'get',
        params
    })
}

/* 永久删除员工方法 */
export function delUser(params) {
    
    
  return request({
    
    
    url: 'http://127.0.0.1:9007/sys/recycle/del',
    method: 'delete',
	params
  })
}

/* 用户恢复方法,将数据恢复到sys_user表中 */
export function restore(params) {
    
    
  return request({
    
    
    url: 'http://127.0.0.1:9007/sys/recycle/restoreUser',
    method: 'post',
	params
  })
}
在这里插入代码片

3. Recycle bin implementation method

 //回收站功能已实现05.30
    handleRestore(index, row) {
    
    
      var that = this;
      this.$confirm(
        "此操作将还原用户: " + row.username + " , 是否继续?",
        "提示",
        {
    
    
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
    
    
          //定义回收的参数,分别是id,用户名,邮箱,密码,修改时间,状态,角色
          var params = {
    
    
            id: row.id, //用户id
            username: row.username, //用户名
            email: row.email, //用户邮箱
            password: row.password, //用户密码
            modifyTime: row.modifyTime, //用户修改时间
            role: row.role, //用户角色
            state: row.state, //用户状态
          };
          restore(params).then(); /* 调用api的后端回收方法,在回收的同时,将数据删除 */
          delUser(params).then((res) => {
    
    /*调用api的后端删除方法*/
            if (res.code == 200 && res.success == "success" && res.data >= 1) {
    
    
              this.$message({
    
    
                type: "success",
                message: "还原" + row.username + "成功!",
              });
              this.queryUserList();
            } else {
    
    
              this.$message({
    
    
                type: "success",
                message: "还原" + row.username + "失败!",
              });
            }
          });
        })
        .catch(() => {
    
    
          //点击取消
          this.$message({
    
    
            type: "info",
            message: "已取消还原",
          });
        });
    },

Second, the method implementation of the back-end interface

1. Write a recycling user entity class

/**
 * @author kk
 * @version 1.0
 * @date 2021/5/19 11:40
 * 用户回收信息实体
 */
@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class RecycleUser {
    
    
    private Integer id;//角色id
    private String username;//用户名
    private String password;//用户密码
    private String email;//用户邮箱
    private String role;//用户角色
    private Boolean state;//用户状态,判断是否能够进入后台
    private Integer userId;//角色id
    private Date modifyTime;//用户修改时间
    private Date createTime;//用戶创建时间
}

2. Control layer

/**
 * @author kk
 * @version 1.0
 * @date 2021/5/19 12:23
 * 回收用户控制层
 */
@RestController
@RequestMapping(value = "/sys/recycle")
public class RecycleUserController {
    
    
    @Resource
    RecycleUserService recycleUserService;

    @RequestMapping(value = "/list")
    public ObjectResult<PageInfo<RecycleUser>> getAllDept(@RequestParam(value = "name", required = false) String username,
                                                          @RequestParam(value = "pageIndex", required = false, defaultValue = "1") Integer pageIndex,
                                                          @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize)
    {
    
    
        PageInfo <RecycleUser> pageInfo = recycleUserService.list(username, pageIndex, pageSize);
        return ResultUtil.okObjectResult(pageInfo);
    }

    //在前端通过发送员工id查询到员工消息,并将查询到的数据返回给前端
    @RequestMapping(value = "/getUserInfo")
    public ObjectResult<RecycleUser> getById(@RequestParam("id")Integer id) {
    
    
        RecycleUser recycleUser = recycleUserService.findById(id);
        return ResultUtil.okObjectResult(recycleUser);
    }


    //还原方法的提交映射
    @PostMapping(value = "/restoreUser")
    public ObjectResult restore(@RequestParam(value = "username") String username,
                                @RequestParam(value = "id")Integer id,
                                @RequestParam(value = "password") String password,
                                @RequestParam(value = "role") String role,
                                @RequestParam(value = "state") Boolean state,
                                @RequestParam(value = "email") String email){
    
    
        RecycleUser recycle=new RecycleUser();//实例化一个对象
        recycle.setUsername(username);//设置用户名
        recycle.setId(id);//设置用户id
        recycle.setPassword(password);//设置密码
        recycle.setRole(role);//设置用户角色
        recycle.setState(state);//设置用户状态
        recycle.setUserId(2);//设置初始化用户id,默认为2
        recycle.setEmail(email);//设置用户邮箱
        recycle.setCreateTime(new Date());//设置创建时间,根据当前时间插入
        recycle.setModifyTime(new Date());//设置修改时间,根据当前时间插入
        int count = recycleUserService.restore(recycle);
        return ResultUtil.okObjectResult(count);
    }

    //删除用户方法,根据id号来执行删除,接口为/sys/recycle/del
    @RequestMapping(value = "/del")
    public ObjectResult deleteUser(@RequestParam(value = "id") Integer id) {
    
    
        System.out.println("删除用户"+id+"成功");
        return ResultUtil.okObjectResult(recycleUserService.del(id));
    }

    /* 自定义日期转换格式,解决前端传输来的数据无法转换成Date类型 */
    @InitBinder
    public void InitBinder (ServletRequestDataBinder binder){
    
    
        binder.registerCustomEditor(java.util.Date.class,
                new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true)
        );
    }
}

3.1 Service layer

/**
 * @author kk
 * @version 1.0
 * @date 2021/5/30 12:29
 */
@Service
public interface RecycleUserService {
    
    
    /**
     * 条件查询
     * @param username
     * @param pageIndex 页码
     * @param pageSize 每页条数
     * @return
     */
    PageInfo <RecycleUser> list(String username,Integer pageIndex,Integer pageSize);

    /**
     * 条件查询
     * @param id
     * @return
     */
    RecycleUser findById(Integer id);

    /**
     * 还原用户信息
     * @param recycleUser
     * @return
     */
    int restore(RecycleUser recycleUser);
    
    /**
     * 彻底删除用户信息
     * @param id
     * @return
     */
    int del(Integer id);
}

3.2 Service layer implementation class

/**
 * @author kk
 * @version 1.0
 * @date 2021/5/30 12:30
 */
@Service
@Transactional
public class RecycleUserServiceImpl implements RecycleUserService {
    
    

    @Resource
    RecycleUserMapper recycleUserMapper;//注入Mapper层

    /*显示在回收站用户信息服务*/
    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    @Override
    public PageInfo <RecycleUser> list(String username, Integer pageIndex, Integer pageSize) {
    
    
        PageHelper.startPage(pageIndex,pageSize);
        List <RecycleUser> list = recycleUserMapper.getAllUserList(username);
        return new PageInfo<>(list);
    }

    /*根据用户id查询到信息服务*/
    @Transactional(propagation = Propagation.REQUIRED,readOnly = false)
    @Override
    public RecycleUser findById(Integer id) {
    
    
        return recycleUserMapper.getById(id);
    }

    /*还原用户信息方法服务*/
    @Transactional(propagation = Propagation.REQUIRED,readOnly = false)
    @Override
    public int restore(RecycleUser recycleUser) {
    
    
        return recycleUserMapper.restoreUser(recycleUser);
    }

    /*删除用户信息服务,根据id进行删除*/
    @Transactional(propagation = Propagation.REQUIRED,readOnly = false)
    public int del(Integer id) {
    
     return recycleUserMapper.deleteUser(id); }
}

4. Dao layer

/**
 * @author kk
 * @version 1.0
 * @date 2021/5/30 12:24
 */
@Mapper
@Transactional
public interface RecycleUserMapper {
    
    
    List <RecycleUser> getAllUserList(@Param(value = "username")String username);//获得所有的用户信息方法
    int restoreUser(RecycleUser recycleUser);//恢复功能实现
    RecycleUser getById(@Param(value = "id")Integer id);//根据用户id值,查询用户信息
    int deleteUser(@Param(value = "id")Integer id);//删除在回收站的用户
}

5.xml writing

<!--id值对应mapper下的方法名字,查询到表中的信息-->
<mapper namespace="com.jk4.recycle.dao.RecycleUserMapper">
    <select id="getAllUserList" resultType="RecycleUser">
        select * from sys_recycle_user
        <trim prefix="WHERE" prefixOverrides="and|or">
            <if test="username!=null and username!=''">
                where username LIKE #{username}
            </if>
        </trim>
    </select>


    <!--根据id值查询到当前用户信息-->
    <select id="getById" resultType="RecycleUser">
        SELECT * FROM sys_recycle_user WHERE id=#{id}
    </select>

    <!--回收站功能核心:实现原理将即将删除的用户信息插入到sys_user表中-->
    <insert id="restoreUser" parameterType="RecycleUser">
        INSERT into sys_user(username,password,email,role,state,createTime)
        value(#{username},#{password},#{email},#{role},#{state},#{createTime})
    </insert>

    <!--根据用户id删除信息-->
    <delete id="deleteUser">
        delete from sys_recycle_user where id=#{id}
    </delete>
</mapper>

6. The last step (important)

The last important step is to add recycling methods in UserController, UserMapper, UserService, UserServiceImpl, and xml files respectively

6.1UserController

 //回收用户方法,调用服务层的方法,使用工具类返回json格式,还未实现
    @RequestMapping(value = "/recycle")
    public ObjectResult recycleUser(
                                    @RequestParam(value = "username") String username,
                                    @RequestParam(value = "id")Integer id,
                                    @RequestParam(value = "password") String password,
                                    @RequestParam(value = "role") String role,
                                    @RequestParam(value = "state") Boolean state,
                                    @RequestParam(value = "email") String email){
    
    
        User user =new User();//实例化一个User对象
        user.setUsername(username);//更改用户名
        user.setId(id);//更改用户id
        user.setPassword(password);//更改用户密码
        user.setRole(role);//更改用户角色
        user.setState(state);//更改用户状
        user.setEmail(email);//更改用户邮箱
        user.setUserId(2);//更改初始化用户id,默认为2
        user.setModifyTime(new Date());//根据当前时间设置修改时间
        int count = userService.recycle(user);
        return ResultUtil.okObjectResult(count);//返回处理的数据结果集
    }

6.2UserMapper

int recycle(User user);

6.3UserService

 /**
     * 回收用户服务
     * @param user
     * @return
     */
    int recycle(User user);

6.4UserServiceImpl

  /*回收用户信息实现*/
    @Override
    @Transactional(propagation = Propagation.REQUIRED,readOnly = false)
    public int recycle(User user) {
    
    
        return userMapper.recycle(user);
    }

6.5xml

The idea of ​​​​implementation is here to insert data into the recycling table.

<!--新增用户的映射文件-->
    <insert id="recycle" parameterType="User">
        INSERT into sys_recycle_user (username,password,email,role,state,modifyTime,userId)
        value(#{username},#{password},#{email},#{role},#{state},#{modifyTime},#{userId})
    </insert>

7. Page realization

I forgot to take a screenshot of the page implementation, and I will make it up next time!

Summarize

Next time there will be an issue of front-end performance optimization, which will be very useful for front-end novices hahahaha.

Guess you like

Origin blog.csdn.net/weixin_45331887/article/details/117430610