CMS客户关系管理系统【中】
发布于 4 年前 作者 yan16 4170 次浏览 来自 分享

CMS客户关系管理系统【中】

引言:此文承接上一篇cms文章:https://developers.weixin.qq.com/community/develop/article/doc/000ca6404188a0e898fa5080056c13

4.修改UserController

 /**
     * 查询分页数据
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取前端参数
        String page = req.getParameter("page");
        String limit = req.getParameter("limit");
        String realname = req.getParameter("realname");
        String role = req.getParameter("role");
        String delete = req.getParameter("delete");
        //将参数封装为map
        Map<String,String> params = new HashMap<>();
        if (StrUtil.isNotBlank(realname)){
            params.put("realname",realname);
        }
        if (StrUtil.isNotBlank(role)){
            params.put("role",role);
        }
        if (StrUtil.isNotBlank(delete)){
            params.put("delete",delete);
        }
        Result rs = userService.queryPage(params,page,limit);
        RespUtil.writer(rs,resp);
    }

5.修改IUserService

    /**
     * 分页查询用户列表
     * @param params
     * @param page
     * @param limit
     * @return
     */
    Result queryPage(Map<String, String> params, String page, String limit);

6.修改UserServiceImpl

 [@Override](/user/Override)
    public Result queryPage(Map<String, String> params, String page, String limit) {
        PageInfo<User> pageInfo = userDao.selectPage(params,page,limit);
        return new Result(pageInfo);
    }

7.修改UserDao

    /**
     * 分页查询用户信息
     * @param params
     * @param page
     * @param limit
     * @return
     */
    public PageInfo<User> selectPage(Map<String, String> params, String page, String limit) {
        String sql = "select id,username,password,role,realname,`delete`,img,create_time as createTime from user where 1=1 ";
        if (params.containsKey("realname")){
            sql = sql +" and realname like concat('%','"+params.get("realname")+"','%') ";
        }
        if (params.containsKey("role")){
            sql = sql +" and role = "+params.get("role");
        }
        if (params.containsKey("delete")){
            sql = sql +" and `delete` = "+params.get("delete");
        }
        return  super.selectPage(sql,User.class,Integer.parseInt(page),Integer.parseInt(limit));
    }

新增员工

新增员工:(头工具栏监听事件)

  1. 点击新增
  2. 弹出一个层
  3. 填写员工信息
  4. 将员工信息插入数据库

1.新增按钮模板

    <%-- 头工具栏 --%>
    <script type="text/html" id="headerBtns">
        <button class="layui-btn layui-btn-sm" lay-event="add">
            <i class="layui-icon layui-icon-add-1"></i> 新增
        </button>
    </script>
    <%-- 行工具栏 --%>
    <script type="text/html" id="rowBtns">
        <div class="layui-btn-group">
            <button class="layui-btn layui-btn-xs layui-btn-warm" lay-event="reset">
                <i class="layui-icon layui-icon-edit"></i> 重置密码
            </button>
            <button class="layui-btn layui-btn-xs  layui-btn-danger" lay-event="del">
                <i class="layui-icon layui-icon-delete"></i> 离职
            </button>
        </div>
    </script>

2.修改表格渲染参数

新增:toolbar属性

let opt = {
         id:"dataTableId",
         elem:"#dataTable",
         url:"${pageContext.request.contextPath}/user.do?service=page",
         toolbar:"#headerBtns",//
         cols:[[
             {type:"checkbox"},
             {field:"username",title:"用户名"},
             {field:"password",title:"密码"},
             {field:"realname",title:"用户名"},
             {field:"role",title:"角色",templet:function (d) {
                 let role = d.role;
                 if (role == 1){
                     return "<b style='color: #5FB878'>管理员</b>"
                 }else if (role == 2){
                     return "<b style='color: red'>业务员</b>"
                 }
             }},
             {field:"delete",title:"状态",templet:function (d) {
                     let del = d.delete;
                     if (del == 1){
                         return "<b style='color: #5FB878'>在职</b>"
                     }else if (del == 2){
                         return "<b style='color: red'>离职</b>"
                     }
                 }},
             {field:"createTime",title:"创建时间"},
             {title:"操作",toolbar:"#rowBtns"},
         ]],
         page:true,
         parseData:function (rs) {
             return {
                 "code" : rs.code,
                 "msg":rs.msg,
                 "count":rs.data.total,
                 "data":rs.data.data
             }
         },
         response:{
             statusCode:200
         }
 };

3.新增头工具栏监听事件

  //头工具栏监听事件
        table.on("toolbar(dataTableFilter)",function (d) {
            let event = d.event;
            if (event == "add"){
                //新增用户信息
                add();
            }
        });

4.新增弹层模板

 <%-- 更新数据模板 --%>
    <script type="text/html" id="editTpls">
        <div style="padding: 20px">
            <form class="layui-form layui-form-pane" id="editForm" lay-filter="editFormFilter">
                <div class="layui-form-item">
                    <label class="layui-form-label">用户名</label>
                    <div class="layui-input-inline">
                        <input type="text" name="realName" class="layui-input" placeholder="用户姓名" autocomplete="off" lay-verify="required" lay-reqText="请输入用户姓名" >
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">登录名</label>
                    <div class="layui-input-inline">
                        <input type="text" name="username" class="layui-input" placeholder="登录名" autocomplete="off" lay-verify="required" lay-reqText="请输入登录名" >
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">密码</label>
                    <div class="layui-input-inline">
                        <input type="text" name="password" class="layui-input" placeholder="密码" readonly value="123456" >
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">角色</label>
                    <div class="layui-input-inline" style="width: 210px">
                        <input type="radio" name="role"  title="管理员" value="1" >
                        <input type="radio" name="role"  title="业务员" value="2" checked>
                    </div>
                </div>
                <button type="button" style="display: none" id="subBtn" lay-submit lay-filter="subBtnFilter"></button>
            </form>
        </div>
    </script>

5.新增具体的处理新增的方法

   //具体的新增方法
        function add() {
            //弹出层
            layer.open({
                title:"编辑",
                type:1,//页面层
                content:$("#editTpls").html(),//页面内容
                area:"380px",
                btn:['确认','取消'],
                btnAlign:"c",//按钮居中
                success:function (layero,index) {
                    form.render();
                    //设置表单提交监听事件
                    form.on("submit(subBtnFilter)",function (formData) {
                        //使用ajax提交数据
                        $.post("${pageContext.request.contextPath}/user.do?service=add",formData.field,function (rs) {
                            if (rs.code != 200){
                                layer.msg(rs.msg);
                                return false;
                            }
                            //刷新表格
                            $("#searchBtn").click();
                            //关闭弹层
                            layer.close(index);
                        })
                        return false;//阻止表单默认提交行为
                    });
                },
                yes:function (index,layero) {//点击确认按钮
                    $("#subBtn").click();
                }
            });
        }

6.在UserController中新增代码

 /**
     * 处理客户端新增请求
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String realName = req.getParameter("realName");
        String username = req.getParameter("username");
        String role = req.getParameter("role");
        String time = DateUtil.format(new Date(),Constant.YYYY_MM_DD_HH_MM_SS);
        User user = new User(0,username,Constant.DEFAULT_PASSWORD,realName,Integer.parseInt(role),Constant.USER_STATE_VALID,"",time,time,"");
        Result rs = userService.addUser(user);
        RespUtil.writer(rs,resp);
    }

7.修改IUserService

    /**
     * 新增用户信息
     * @param user
     * @return
     */
    Result addUser(User user);

8.修改UserServiceImpl

    [@Override](/user/Override)
    public Result addUser(User user) {
        //新增用户信息
        //业务数据校验
        User u = userDao.selectOneByName(user.getUsername());
        //校验用户名是否已经被使用
        if (u != null){
            return  new Result(CodeMsg.USER_USERNAME_EXIST_ERROR);
        }
        //新增数据
        userDao.insert(user);
        return new Result();
    }

9.修改UserDao

    /**
     *  新增用户
     * @param user
     */
    public void insert(User user) {
        String sql = "insert into user ( `username`, `password`, `realname`, `role`, `delete`, `create_time`, `modify_time`) value(?,?,?,?,?,?,?)";
        super.update(sql,user.getUsername(),user.getPassword(),user.getRealname(),user.getRole(),user.getDelete(),user.getCreateTime(),user.getModifyTime());
    }

重置密码

重置密码:

  1. 点击重置密码按钮
  2. 进行二次确认
  3. 将用户ID传给后台
  4. 将用户密码进行重置

1.行监听事件

       //行监听事件
        table.on("tool(dataTableFilter)",function (d) {
            let event = d.event;
            if (event == "reset"){
                reset(d.data);
            }else if (event == "del"){
                del(d.data);
            }
        });

2.具体重置的方法

   //具体重置密码的方法
        function  reset(rowData) {
            let deleted = rowData.delete;
            if (deleted == 2){
                layer.msg("用户已离职,无需重置!");
                return false;
            }
            layer.confirm("确定要重置密码吗?",function (index) {
                $.get("${pageContext.request.contextPath}/user.do?service=reset",{id:rowData.id},function (rs) {
                    layer.msg(rs.msg);
                    $("#searchBtn").click();
                    layer.close(index);
                });
            });
        }

3.修改UserController

    /**
     * 重置用户密码
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void reset(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        Result rs = userService.resetPassword(id);
        RespUtil.writer(rs,resp);
    }

4.修改IUserService

   /**
     * 重置用户密码
     * @param id
     * @return
     */
    Result resetPassword(String id);

5.修改UserServiceImpl

    [@Override](/user/Override)
    public Result resetPassword(String id) {
        userDao.updatePassword(id,Constant.DEFAULT_PASSWORD);
        return new Result();
    }

6.修改UserDao

   /**
     * 修改用户密码
     * @param id
     * @param password
     */
    public void updatePassword(String id, String password) {
        String sql = "update user set password = ? ,modify_time = ? where id=?";
        String time = DateUtil.format(new Date(), Constant.YYYY_MM_DD_HH_MM_SS);
        super.update(sql,password,time,id);
    }

删除用户

删除用户:员工离职,就是修改用户的状态

  1. 点击离职
  2. 进行状态判定 如果已经离职 无需再离职
  3. 将用户ID 传给后台
  4. 进行修改状态操作:判断用户是否存在关联客户 如果存在则不进行修改状态 返回错误的业务信息
  5. 将信息展示

1.具体离职方法

    //具体的离职方法
        function  del(rowData) {
            let deleted = rowData.delete;
            if (deleted == 2){
                layer.msg("用户已离职!");
                return false;
            }
            layer.confirm("确定要离职吗?",function (index) {
                $.get("${pageContext.request.contextPath}/user.do?service=delete",{id:rowData.id},function (rs) {
                    layer.msg(rs.msg);
                    $("#searchBtn").click();
                    layer.close(index);
                });
            });
        }

2.修改UserController

    /**
     * 处理用户离职请求
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        Result rs = userService.delete(id);
        RespUtil.writer(rs,resp);
    }

3.修改IUservice

   /**
     * 用户离职业务
     * @param id
     * @return
     */
    Result delete(String id);

4.修改CustomerDao

    /**
     * 根据用户ID 查询客户列表
     * @param userId
     * @return
     */
    public List<Customer> selectListByUser(Integer userId){
        String sql = "select id from customer where user_id = ?";
        return  super.selectList(sql,Customer.class,userId);
    }

5.修改UserServiceImpl

  	CustomerDao customerDao = new CustomerDao();
	
	[@Override](/user/Override)
    public Result delete(String id) {
        //业务处理
        //1.判断用户是否存在客户  使用用户ID 查询客户信息
        List<Customer> customers = customerDao.selectListByUser(Integer.parseInt(id));
        if (!customers.isEmpty()){
            return  new Result(CodeMsg.USER_HAS_CUSTOMER_DELETE_ERROR);
        }
        //修改用户状态
        userDao.updateUserState(id,Constant.USER_STATE_INVALID);
        return new Result();
    }

6.修改UserDao

    /**
     * 修改用户状态
     * @param id
     * @param state
     */
    public void updateUserState(String id, Integer state) {
        String sql = "update user set `delete` = ? ,modify_time = ?,delete_time = ? where id=?";
        String time = DateUtil.format(new Date(), Constant.YYYY_MM_DD_HH_MM_SS);
        super.update(sql,state,time,time,id);
    }

客户列表

客户列表:

​ 将客户信息和相关的业务员信息展示。

搜索条件

  1. 根据业务员进行搜索
  2. 根据客户名称模糊搜
  3. 根据性别搜索
  4. 根据手机号搜索
  5. 根据生日范围搜索

1.新建customer文件夹

2.新增list.jsp

<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false" language="java" %>
<html>
<head>
    <title>Title</title>
    <%-- 引入layui --%>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/resources/layui/css/layui.css">
</head>
<body>
    <div>
        <form  class="layui-form layui-form-pane">
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">业务员</label>
                    <div class="layui-input-inline">
                        <select  id="userId">
                            <option value="">业务员</option>
                        </select>
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">客户</label>
                    <div class="layui-input-inline">
                        <input type="text" class="layui-input" id="name" placeholder="客户" autocomplete="off">
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">性别</label>
                    <div class="layui-input-inline">
                        <select id="sex">
                            <option value="">性别</option>
                            <option value="1">男</option>
                            <option value="2">女</option>
                        </select>
                    </div>
                </div>

            </div>
            <%---------------------------------------------------------%>
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">手机号</label>
                    <div class="layui-input-inline">
                        <input type="text" class="layui-input" id="phone" placeholder="手机号" autocomplete="off">
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">生日</label>
                    <div class="layui-input-inline">
                        <input type="text" class="layui-input" id="birth" placeholder="生日" autocomplete="off" readonly>
                    </div>
                </div>
                <div class="layui-inline">
                    <button type="button" id="searchBtn" class="layui-btn">查询</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>
        <hr>
        <table id="dataTable" lay-filter="dataTableFilter"></table>
    </div>
    <%-- 头工具栏 --%>
    <script type="text/html" id="headerBtns">

        <div class="layui-btn-group">
            <button class="layui-btn layui-btn-sm" lay-event="add">
                <i class="layui-icon layui-icon-add-1"></i> 新增
            </button>
            <button class="layui-btn layui-btn-sm  layui-btn-warm" lay-event="setSaleseman">
                <i class="layui-icon layui-icon-delete"></i> 设置业务员
            </button>
        </div>

    </script>
    <%-- 行工具栏 --%>
    <script type="text/html" id="rowBtns">
        <div class="layui-btn-group">
            <button class="layui-btn layui-btn-xs layui-btn-warm" lay-event="update">
                <i class="layui-icon layui-icon-edit"></i> 修改
            </button>
            <button class="layui-btn layui-btn-xs" lay-event="visit">
                <i class="layui-icon layui-icon-release"></i> 拜访
            </button>
            <button class="layui-btn layui-btn-xs  layui-btn-danger" lay-event="del">
                <i class="layui-icon layui-icon-delete"></i> 删除
            </button>
        </div>
    </script>

    <script src="${pageContext.request.contextPath}/resources/layui/layui.js"></script>
<script>
    layui.use(['form','table','jquery','layer','laydate'],function () {
        let form = layui.form;
        let table = layui.table;
        let $ = layui.jquery;
        let layer = layui.layer;
        let laydate = layui.laydate;

        laydate.render({
            elem:"#birth",
            range:"~"
        })

        //渲染表格
        let opt = {
            id:"dataTableId",
            elem:"#dataTable",
            url:"${pageContext.request.contextPath}/customer.do?service=page",
            toolbar:"#headerBtns",//
            cols:[[
                {type:"checkbox"},
                {field:"name",title:"客户名称",minWidth:120},
                {field:"sex",title:"性别",templet:function (d) {
                        let sex = d.sex;
                        if (sex == 1){
                            return "<b style='color: #5FB878'>男</b>"
                        }else if (sex == 2){
                            return "<b style='color: red'>女</b>"
                        }
                    }},
                {field:"phone",title:"电话",minWidth:120},
                {field:"salary",title:"工资",minWidth:100},
                {field:"birth",title:"生日",minWidth:120},
                {field:"delete",title:"状态",templet:function (d) {
                        let del = d.delete;
                        if (del == 1){
                            return "<b style='color: #5FB878'>有效</b>"
                        }else if (del == 2){
                            return "<b style='color: red'>无效</b>"
                        }
                    }},
                {field:"realname",title:"业务员",minWidth:120},
                {field:"address",title:"地址",minWidth:180},
                {field:"createTime",title:"创建时间",minWidth:170},
                {title:"操作",toolbar:"#rowBtns",minWidth:200,fixed:"right"},
            ]],
            page:true,
            parseData:function (rs) {
                return {
                    "code" : rs.code,
                    "msg":rs.msg,
                    "count":rs.data.total,
                    "data":rs.data.data
                }
            },
            response:{
                statusCode:200
            }

        };
        let tabIns = table.render(opt);
        //表格查询
        $("#searchBtn").click(function () {
            let userId = $("#userId").val();
            let name = $("#name").val();
            let sex = $("#sex").val();
            let phone = $("#phone").val();
            let birth = $("#birth").val();

            tabIns.reload({
                where:{
                    userId:userId,
                    name:name,
                    "sex":sex,
                    "phone":phone,
                    "birth":birth,
                }
            })
        });
        //头工具栏监听事件
        table.on("toolbar(dataTableFilter)",function (d) {
            let event = d.event;
            if (event == "add"){
                //add();
            }else if (event == "setSaleman"){
                //updateUser();
            }
        });
        //行监听事件
        table.on("tool(dataTableFilter)",function (d) {
            let event = d.event;
            if (event == "update"){
            }else if (event == "visit"){
            }else if (event == "del"){
            }
        });

    });
</script>
</body>
</html>

3.修改main.jsp

<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false" language="java" %>
<html>
<head>
    <title>Title</title>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/resources/layui/css/layui.css">
</head>
<body class="layui-layout-body">
<div class="layui-layout layui-layout-admin">
    <div class="layui-header">
        <div class="layui-logo">CMS管理系统</div>
        <!-- 头部区域(可配合layui已有的水平导航) -->
        <ul class="layui-nav layui-layout-left">
        </ul>
        <ul class="layui-nav layui-layout-right">
            <li class="layui-nav-item">
                <a href="javascript:;">
                    <img onerror="javascript:this.src='${pageContext.request.contextPath}/imgs/default.jpg';" src="${pageContext.request.contextPath}/${user.img}" class="layui-nav-img">
                    ${user.realname}
                </a>
            </li>
            <li class="layui-nav-item"><a href="user.do?service=loginOut">退了</a></li>
        </ul>
    </div>

    <div class="layui-side layui-bg-black">
        <div class="layui-side-scroll">
            <!-- 左侧导航区域(可配合layui已有的垂直导航) -->
            <ul class="layui-nav layui-nav-tree"  lay-filter="test">
                <li class="layui-nav-item layui-nav-itemed">
                    <a class="" href="javascript:;">基础信息管理</a>
                    <dl class="layui-nav-child">
                        <dd><a href="page.do?service=userList" target="content">员工管理</a></dd>
                        <dd><a href="page.do?service=customerList" target="content">客户管理</a></dd>
                    </dl>
                </li>
                <li class="layui-nav-item">
                    <a href="javascript:;">系统管理</a>
                    <dl class="layui-nav-child">
                        <dd><a href="javascript:;">密码管理</a></dd>
                        <dd><a href="javascript:;">头像管理</a></dd>
                    </dl>
                </li>
                <li class="layui-nav-item"><a href="javascript:;">数据分析</a>
                    <dl class="layui-nav-child">
                        <dd><a href="javascript:;">拜访占比</a></dd>
                    </dl>

                </li>
            </ul>
        </div>
    </div>

    <div class="layui-body">
        <!-- 内容主体区域 -->
        <div style="padding: 15px;">
            <iframe name="content" style="width: 100%;height: 100%;border: 0px"></iframe>
        </div>
    </div>

    <div class="layui-footer">
        <!-- 底部固定区域 -->
        © layui.com - 底部固定区域
    </div>
</div>
<script src="${pageContext.request.contextPath}/resources/layui/layui.js"></script>
<script>
    //JavaScript代码区域
    layui.use('element', function(){
        var element = layui.element;

    });
</script>
</body>
</html>

4.修改CustomerController

package com.sxt.controller;

import cn.hutool.core.util.StrUtil;
import com.sxt.common.Result;
import com.sxt.service.ICustomerService;
import com.sxt.service.impl.CustomerServiceImpl;
import com.sxt.util.RespUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * [@Description](/user/Description): 客户控制类
 * [@author](/user/author): Mr.T
 * [@date](/user/date) 2020-09-15 15:49
 */
[@WebServlet](/user/WebServlet)("/customer.do")
public class CustomerController extends HttpServlet {

    private ICustomerService customerService;

    [@Override](/user/Override)
    public void init() throws ServletException {
        customerService = new CustomerServiceImpl();
    }

    [@Override](/user/Override)
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String service = req.getParameter("service");
        try {
            Method method = this.getClass().getDeclaredMethod(service, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this,req,resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取前端参数
        String page = req.getParameter("page");
        String limit = req.getParameter("limit");
        String userId = req.getParameter("userId");
        String name = req.getParameter("name");
        String sex = req.getParameter("sex");
        String phone = req.getParameter("phone");
        String birth = req.getParameter("birth");
        //将参数封装为map
        Map<String,String> params = new HashMap<>();
        if (StrUtil.isNotBlank(userId)){
            params.put("userId",userId);
        }
        if (StrUtil.isNotBlank(name)){
            params.put("name",name);
        }
        if (StrUtil.isNotBlank(sex)){
            params.put("sex",sex);
        }
        if (StrUtil.isNotBlank(phone)){
            params.put("phone",phone);
        }
        if (StrUtil.isNotBlank(birth)){
          String[] births = birth.split("~");
            params.put("minBirth",births[0].trim());
            params.put("maxBirth",births[1].trim());
        }
        Result rs = customerService.queryPage(params,page,limit);
        RespUtil.writer(rs,resp);
    }
}

5.修改ICustomerService

   /**
     * 分页查询客户信息
     * @param params
     * @param page
     * @param limit
     * @return
     */
    Result queryPage(Map<String, String> params, String page, String limit);

6.修改CustomerServiceImpl

    CustomerDao customerDao = new CustomerDao();
    [@Override](/user/Override)
    public Result queryPage(Map<String, String> params, String page, String limit) {
        PageInfo<Customer> pageInfo = customerDao.selectPage(params,page,limit);
        return new Result(pageInfo);
    }

7.修改CustomerDao

 /**
     * 分页查询数据
     * @param params
     * @param page
     * @param limit
     * @return
     */
    public PageInfo<Customer> selectPage(Map<String, String> params, String page, String limit) {
        String sql = "select  c.`id`, c.`name`, c.`sex`, c.`phone`, c.`salary`, c.`address`, c.`birth`, c.`delete`, c.`user_id` as userId,u.realname,c.create_time as createTime from customer c LEFT JOIN `user` u on c.user_id = u.id where 1=1 ";

        if (params.containsKey("name")){
            sql = sql +" and c.name like concat('%','"+params.get("name")+"','%') ";
        }
        if (params.containsKey("sex")){
            sql = sql +" and c.sex = "+params.get("sex");
        }
        if (params.containsKey("phone")){
            sql = sql +" and c.phone = "+params.get("phone");
        }
        if (params.containsKey("userId")){
            sql = sql +" and c.`user_id` = "+params.get("userId");
        }
        if (params.containsKey("minBirth")){
            sql = sql +" and c.`birth` >= '"+params.get("minBirth")+"'";
        }
        if (params.containsKey("maxBirth")){
            sql = sql +" and c.`birth` <= '"+params.get("maxBirth")+"'";
        }
        return  super.selectPage(sql,Customer.class,Integer.parseInt(page),Integer.parseInt(limit));
    }

8.修改Customer实体类

在Customer类中,新增realname属性

新增客户

新增客户:

  1. 点击新增按钮
  2. 弹出新增模板层
  3. 将模板层中的数据使用ajax提交(新增和后续修改使用一个模板层),客户的业务员从当前用户获取
  4. 新增成功更新表格数据

1.修改list.jsp,新增模板

 <%-- 更新数据模板 --%>
    <script type="text/html" id="editTpls">
        <div style="padding: 20px">
            <form class="layui-form layui-form-pane" id="editForm" lay-filter="editFormFilter">
                <div class="layui-form-item">
                    <label class="layui-form-label">客户名称</label>
                    <div class="layui-input-inline">
                        <input type="text" name="name" class="layui-input" placeholder="客户名称" autocomplete="off" lay-verify="required" lay-reqText="请输入客户名称" >
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">性别</label>
                    <div class="layui-input-inline">
                        <input type="radio" name="sex"  title="男" value="1" >
                        <input type="radio" name="sex"  title="女" value="2" checked>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">生日</label>
                    <div class="layui-input-inline">
                        <input type="text" name="birth" class="layui-input" placeholder="生日" autocomplete="off" lay-verify="required" lay-reqText="请输入客户生日" id="editBirth"  readonly >
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">手机号</label>
                    <div class="layui-input-inline">
                        <input type="text" name="phone" class="layui-input" placeholder="手机号" autocomplete="off" lay-verify="required|phone" lay-reqText="请输入客户手机号" >
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">月薪</label>
                    <div class="layui-input-inline">
                        <input type="text" name="salary" class="layui-input" placeholder="月薪" autocomplete="off" lay-verify="required|number" lay-reqText="请输入客户月薪" >
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">地址</label>
                    <div class="layui-input-inline">
                        <input type="text" name="address" class="layui-input" placeholder="地址" autocomplete="off" lay-verify="required" lay-reqText="请输入客户地址"    >
                    </div>
                </div>
                <button type="button" style="display: none" id="subBtn" lay-submit lay-filter="subBtnFilter"></button>
            </form>
        </div>
    </script>

2.具体的新增方法

注意: 在头工具栏事件中 调用具体的新增方法

let layerOpt = {
            title:"编辑",
            type:1,//页面层
            content:$("#editTpls").html(),//页面内容
            area:"380px",
            btn:['确认','取消'],
            btnAlign:"c",//按钮居中
            success:function (layero,index) {
                form.render();
                laydate.render({elem:"#editBirth"})
                //设置表单提交监听事件
                form.on("submit(subBtnFilter)",function (formData) {
                    //使用ajax提交数据
                    $.post("${pageContext.request.contextPath}/customer.do?service=add",formData.field,function (rs) {
                        if (rs.code != 200){
                            layer.msg(rs.msg);
                            return false;
                        }
                        //刷新表格
                        $("#searchBtn").click();
                        //关闭弹层
                        layer.close(index);
                    })
                    return false;//阻止表单默认提交行为
                });
            },
            yes:function (index,layero) {//点击确认按钮
                $("#subBtn").click();
            }
        };

        //具体的新增方法
        function add() {
            //如果直接使用layerOpt
            //当进行修改时  会修改layerOpt 中success 属性
            //再进行新增 数据提交 会向修改的地址提交
            //所以将layerOpt 进行复制  避免 layerOpt发生属性修改时  影响了新增业务
            let opt = {};
            //对象复制
            Object.assign(opt,layerOpt)
            //弹出层
            layer.open(opt);
        }

3.修改CustomerController

    /**
     * 处理新增请求
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取前端参数
        String name = req.getParameter("name");
        String sex = req.getParameter("sex");
        String phone = req.getParameter("phone");
        String birth = req.getParameter("birth");
        String salary = req.getParameter("salary");
        String address = req.getParameter("address");
        String time = DateUtil.format(new Date(),Constant.YYYY_MM_DD_HH_MM_SS);
        User user = (User) req.getSession().getAttribute(Constant.CURRENT_USER_KEY);
        Customer customer = new Customer(0,name,Integer.parseInt(sex),phone,Integer.parseInt(salary),address,birth, Constant.CUSTOMER_STATE_VALID,user.getId(),time,time,"");
        Result rs = customerService.add(customer);
        RespUtil.writer(rs,resp);
    }

4.修改ICustomerService

    /**
     * 新增客户
     * @param customer
     * @return
     */
    Result add(Customer customer);

5.修改CustomerServiceImpl

  [@Override](/user/Override)
    public Result add(Customer customer) {
        //校验手机号 是否存在
        Customer c = customerDao.selectByPhone(customer.getPhone());
        if (c != null){
            return  new Result(CodeMsg.CUSTOMER_PHONE_USED_ERROR);
        }
        customerDao.insert(customer);
        return new Result();
    }

6.修改CustomerDao

   /**
     * 新增一个客户信息
     * @param customer
     */
    public void insert(Customer customer) {
        String sql = "insert into customer (`name`, `sex`, `phone`, `salary`, `address`, `birth`, `delete`, `user_id`, `create_time`, `modify_time`) value(?,?,?,?,?,?,?,?,?,?)";
        super.update(sql,customer.getName(),customer.getSex(),customer.getPhone(),customer.getSalary(),customer.getAddress(),customer.getBirth(),customer.getDelete(),customer.getUserId(),customer.getCreateTime(),customer.getModifyTime());
    }

业务员下拉框列表

业务员列表:

  1. 在搜索中,需要根据业务员搜索
  2. 业务信息会发生改变,所以业务信息从数据库中获取
  3. 从数据库中获取可用业务员数据
  4. 使用JS在业务员下拉框中,渲染业务员选项
  5. 重新渲染下拉框

1.修改list.jsp

 getSalesman();
        //初始化业务员
        /*
        * 1.获取数据
        * 2.渲染下拉框
        * */
        function getSalesman(){
            $.get("${pageContext.request.contextPath}/user.do?service=getAllUser",{role:2,delete:1},function (rs) {
                let salesman = rs.data;
                //获取业务员下拉框
                let select = $("#userId");
                for (let user of salesman){
                    select.append('<option value="'+user.id+'">'+user.realname+'</option>');
                }
                //重新渲染下拉框
                form.render("select");
            })
        }

2.修改UserController

    /**
     * 根据状态 和 角色获取用户
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void getAllUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String delete = req.getParameter("delete");
        String role = req.getParameter("role");
        Result rs = userService.getAllUser(delete,role);
        RespUtil.writer(rs,resp);
    }

3.修改IUserService

   /**
     * 根据状态和角色获取用户
     * @param delete
     * @param role
     * @return
     */
    Result getAllUser(String delete, String role);

4.修改UserServiceImpl

 [@Override](/user/Override)
    public Result getAllUser(String delete, String role) {
        List<User> users = userDao.selectUsers(Integer.parseInt(role), Integer.parseInt(delete));
        return new Result(users);
    }

5.修改UserDao

package com.sxt.dao;

import cn.hutool.core.date.DateUtil;
import com.sxt.common.BaseDao;
import com.sxt.common.Constant;
import com.sxt.common.PageInfo;
import com.sxt.pojo.User;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * [@Description](/user/Description): 用户数据操作类
 * [@author](/user/author): Mr.T
 * [@date](/user/date) 2020-09-15 15:41
 */
public class UserDao extends BaseDao {
    /**
     * 根据用户名查询用户
     * @param username
     * @return
     */
    public User selectOneByName(String username) {
        String sql = "select id,username,password,realname,role,`delete`,img from user where username=?";
        return super.selectOne(sql,User.class,username);
    }

    /**
     * 分页查询用户信息
     * @param params
     * @param page
     * @param limit
     * @return
     */
    public PageInfo<User> selectPage(Map<String, String> params, String page, String limit) {
        String sql = "select id,username,password,role,realname,`delete`,img,create_time as createTime from user where 1=1 ";
        if (params.containsKey("realname")){
            sql = sql +" and realname like concat('%','"+params.get("realname")+"','%') ";
        }
        if (params.containsKey("role")){
            sql = sql +" and role = "+params.get("role");
        }
        if (params.containsKey("delete")){
            sql = sql +" and `delete` = "+params.get("delete");
        }
        return  super.selectPage(sql,User.class,Integer.parseInt(page),Integer.parseInt(limit));
    }
    /**
     *  新增用户
     * @param user
     */
    public void insert(User user) {
        String sql = "insert into user ( `username`, `password`, `realname`, `role`, `delete`, `create_time`, `modify_time`) value(?,?,?,?,?,?,?)";
        super.update(sql,user.getUsername(),user.getPassword(),user.getRealname(),user.getRole(),user.getDelete(),user.getCreateTime(),user.getModifyTime());
    }

    /**
     * 修改用户密码
     * @param id
     * @param password
     */
    public void updatePassword(String id, String password) {
        String sql = "update user set password = ? ,modify_time = ? where id=?";
        String time = DateUtil.format(new Date(), Constant.YYYY_MM_DD_HH_MM_SS);
        super.update(sql,password,time,id);
    }

    /**
     * 修改用户状态
     * @param id
     * @param state
     */
    public void updateUserState(String id, Integer state) {
        String sql = "update user set `delete` = ? ,modify_time = ?,delete_time = ? where id=?";
        String time = DateUtil.format(new Date(), Constant.YYYY_MM_DD_HH_MM_SS);
        super.update(sql,state,time,time,id);
    }

    /**
     * 根据角色和状态查询用户
     * @param role
     * @param state
     * @return
     */
    public List<User> selectUsers(Integer role ,Integer state) {
        String sql = "select id,realname from user where role = ? and  `delete`=?";
        return super.selectList(sql,User.class,role,state);
    }

}
回到顶部