精华内容
下载资源
问答
  • 客户列表 首先修改main.jsp的跳转路径及PageServlet后台路径的转发,代码如下 <dd><a href="page.do?page=customerList" target="con">客户管理</a></dd> protected void customerList...

    客户列表

    首先修改main.jsp的跳转路径及PageServlet后台路径的转发,代码如下

    <dd><a href="page.do?page=customerList" target="con">客户管理</a></dd>
    protected void customerList(HttpServletRequest req, HttpServletResponse resp) throws
     req.getRequestDispatcher("WEB-INF/jsp/customer/list.jsp").forward(req,resp);
    }
    

    1.1参考用户列表jsp
    重点关注如下内容: code / count / data 的最后一个参数名. 要和当前工程定义的类的属性同名.否
    则列表无数据
    另外,layui默认code响应成功是0. 而工程中定义成功为200 , 那么此处需要明确给出是200

    parseData:function(rs){//数据格式解析
     if(rs.code == 200){
     return {
     "code":rs.code,
     "msg":rs.msg,
     "count":rs.data.total,
     "data":rs.data.list
     }
     }
     },
     response:{ // 设置响应码
     statusCode: 200 //规定成功的状态码,默认:0
     }
    

    1.2CustomerServlet的列表实现

    protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletE
     String page = req.getParameter("page");
     String limit = req.getParameter("limit");
     String cust_name = req.getParameter("cust_name");
     String cust_position = req.getParameter("cust_position"); //职位
     String minTime = req.getParameter("minTime");
     String maxTime = req.getParameter("maxTime");
     String company = req.getParameter("company");
     String cust_phone = req.getParameter("cust_phone");
     String userId = req.getParameter("userId");
     Map<String,Object> map = new HashMap<String, Object>();
     if(!StrUtil.isBlank(cust_name)){
     map.put("cust_name",cust_name);
     }
     if(!StrUtil.isBlank(cust_position)){
     map.put("cust_position",cust_position);
     }
     if(!StrUtil.isBlank(minTime)){
     map.put("minTime",minTime);
     }
     if(!StrUtil.isBlank(maxTime)){
     map.put("maxTime",maxTime);
     }
     if(!StrUtil.isBlank(company)){
     map.put("company",company);
     }
     if(!StrUtil.isBlank(cust_phone)){
     map.put("cust_phone",cust_phone);
     }if(!StrUtil.isBlank(userId)){
     map.put("userId",userId);
     }
     JsonData jsonData = customerService.findCustsByPage(page,limit,map);
     PrintJsonData.printJson(resp,jsonData);
     }
    

    1.3 Customer业务层

    public JsonData findCustsByPage(String page, String limit, Map<String, Object> map) {
     PageBean<Customer> pageBean = customerDao.findCustsByPage(Integer.valueOf(pag
     return JsonData.buildSuc(pageBean);
     }
    

    1.4Customer持久层
    注意:因为客户是属于User(用户) 的 ,和用户是 "多对1"关系,此处为显示关联的客户名,使用外连接
    select u.real_name userRealName , c.
    from t_customer c left join t_user u on u.id=c.user_id where 1=1
    另外在Customer类中,多写1个属性userRealName 记录上面sql查询的用户名的别名*

    public PageBean<Customer> findCustsByPage(Integer page, Integer limit, Map<String, O
     String sql = "select u.real_name userRealName , c.* from t_customer c left jo
     if(map.containsKey("cust_name")){
     sql = sql + " and cust_name like'%"+map.get("cust_name")+"%'";
     }
     if(map.containsKey("cust_position")){
     sql = sql + " and cust_position like'%"+map.get("cust_position")+"%'";
     }
     if(map.containsKey("minTime")){
     sql = sql + " and cust_birth>='"+map.get("minTime")+"'";
     }
     if(map.containsKey("maxTime")){
     sql = sql + " and cust_birth<='"+map.get("maxTime")+"'";
     }
     if(map.containsKey("company")){
     sql = sql + " and company like'%"+map.get("company")+"%'";
     }
     if(map.containsKey("cust_phone")){
     sql = sql + " and cust_phone='"+map.get("cust_phone")+"'";
     }
     if(map.containsKey("userId")){
     sql = sql + " and user_id="+map.get("userId")+"";
     }
     return super.findPage(sql,page,limit,Customer.class);
     }
    

    **1.5 列表页搜索下拉显示
    **
    因为列表页头部的搜索需要下拉显示"用户信息" ,所以在首次跳转到customer.jsp的同时要完成用
    户列表的查询
    注意: 这里是一个同步查询

    protected void customerList(HttpServletRequest req, HttpServletResponse resp) throws
     //查询用户列表并返回
     List<User> list = userService.findUsers(ConstantBean.USER_TYPE); //传入数字2
     req.setAttribute("list",list);
     req.getRequestDispatcher("WEB-INF/jsp/customer/list.jsp").forward(req,resp);
     }
    

    2.更新业务员

    2.1 客户的列表页面查看更新代码

    function setSales(data){
     layer.open({
     id:"setSales",
     title:'设置业务员',
     content:$("#setSalesTemp").html(),
     btn:['提交','取消'],
     area:['500px','500px'],
     yes:function(layero,index){//点击提交时触发
     $("#setSalesFormBtn").click();
     },
     btnAlign:'center',
     success:function(layero,index){// 页面弹出成功触发
     alert(12);
     //获取所有的业务员
     $.ajax({
     url:"user.do",
     dataType:'json',
     data:{'service':'sales'},
     async:false,//设置为同步 --->由于form表单需要重新渲染,若使用异步
     success:function(rs){
     console.log(rs)
     if(rs.code != 200){
     layer.msg(rs.msg);
     return false;
     }
     var sales = rs.data;
     var select = $("#changeUserId");
     $.each(sales,function(index,value){
     select.append("<option value='"+value.id+"'>"+value.r
     });
     }
     });
     //重新渲染表单
     form.render();
     //监听form表单的提交
     form.on("submit(setSalesFormFilter)",function(d){
     console.log("用户id---"+d.field)
     var ids = "";
     $.each(data,function(index,value){
     ids = ids + "id="+value.id+"&"
     });
     //提交数据
     $.post("customer?service=setSales&"+ids,{'userId':d.field.use
     //业务正常
     if(rs.code == 200){
     layer.msg("设置成功");
     //让搜索按钮进行点击 刷新table
     $("#searchBtn").click();
     //关闭弹层
     layer.close(index);
     return false;
     }
     layer.msg(rs.msg);
     });
     return false;//阻止表单默认提交
     });
     }
     });
     }
    

    **2.2注意观察更新的实现
    **
    首先, 需要先可以选择多个"客户" , 其次在弹出框中 ,下拉列表需要查询用户的列表json数据. 所以这里一共有2个操作
    第1个: 获取用户列表的json数据
    第2个:点击"提交"按钮的更新功能
    首先是获取用户列表的json数据 ,如下,和上面获取用户列表调用的是同一个方法

    protected void sales(HttpServletRequest req, HttpServletResponse resp) throws IOExcep
     List<User> users = userService.findUsers(2);//拿到所有业务员
     JsonData jsonData = JsonData.buildSuc(users);
     PrintJsonData.printJson(resp,jsonData);
     }
    

    获取用户列表的 service和dao

    public List<User> findUsers(Integer userType) {
     return userDao.findUsers(userType);
    }
    如果数据表和类属性同名,此处可简写sql
    public List<User> findUsers(Integer userType) {
     String sql = "select id as id,user_name as userName,password as password,real
     return super.findList(sql, User.class, userType);
    }
    

    *其次完成更新功能 ,关于提交选择客户的参数名—浏览器调试查看是多个id
    CustomerServlet
    *

    /**
     * 给 客户 设置 业务员 .注意,可以同时给多个客户 设置同一个业务员
     * 也就是说提交的 客户id是多个
     */
     protected void setSales(HttpServletRequest req, HttpServletResponse resp) throws
     //拿到客户id
     String[] id = req.getParameterValues("id");
     //拿到业务员 id
     String userId = req.getParameter("userId");
     JsonData jsonData = customerService.setSales(id,userId);
     PrintJsonData.printJson(resp,jsonData);
     }
     public JsonData setSales(String[] id, String userId) {
     boolean b = customerDao.updateSalse(id,userId);
     if(b){
     return JsonData.buildSuc("客户业务员更新失败");
     }
     return JsonData.buildSuc("客户业务员更新成功");
     }
    

    CustomerDao

    public boolean updateSalse(String[] id, String userId) {
     String ids = "";
     for(String str:id){
     ids+= str+",";
     }
     ids = ids.substring(0,ids.lastIndexOf(","));//ids=1,2
     //sql传入 ids
     String sql = "update t_customer set user_id=? where id in("+ids+")";
     //注意id已经被赋值到SQL语句中,调用父类方法不需要再传入ids
     return super.update(sql,userId);
     }
    

    3.新增客户

    3.1新增客户前台页面
    在这里插入图片描述

    function add(){
     layer.open({
     id:"add",
     title:'编辑',
     content:$("#editForm").html(),
     btn:['提交','取消'],
     area:['790px','600px'],
     yes:function(layero,index){//点击提交时触发
     $("#submitFormBtn").click();
     },
     btnAlign:'center',
     success:function(layero,index){// 页面弹出成功触发
     //渲染客户生日
     laydate.render({
     elem:"#cust_birth"
     });
     //重新渲染表单
     form.render();
     // 初始化layedit
     var cust_destEditIndex = layedit.build("cust_dest",{
     height:'250px',//设置富文本高度
     hideTool:['image'] ,// 设置隐藏的工具栏
     });
     //为form绑定提交事件
     //为表单新增监听提交事件
     form.on("submit(submitFormFilter)",function(d){
     d.field.cust_dest = layedit.getContent(cust_destEditIndex);
     $.post("customer",d.field,function(rs){
     //业务正常
     if(rs.code == 200){
     layer.msg("新增成功");
     //让搜索按钮进行点击 刷新table
     $("#searchBtn").click();
     //关闭弹层
     layer.close(index);
     return false;
     }
     layer.msg(rs.msg);
     });
     return false;//阻止表单默认提交
     });
     }
      });
     }
    

    **3.2新增客户的后台实现
    **
    *Servlet的实现
    *

    注意: 客户表中关联了user_id , 这个id来源于当前登录的用户,比如某用户"张三"登录了系统,那么他可以给自己"客户"信息

    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletEx
     User user = (User) req.getSession().getAttribute("user");
     //获取参数
     String cust_name = req.getParameter("cust_name");
     String cust_company = req.getParameter("cust_company");
     String cust_position = req.getParameter("cust_position");
     String cust_phone = req.getParameter("cust_phone");
     String cust_birth = req.getParameter("cust_birth");
     String cust_sex = req.getParameter("cust_sex");
     String cust_desc = req.getParameter("cust_desc");
     JsonData jsonData = customerService.add(cust_name,cust_company,cust_position,
     PrintJsonData.printJson(resp,jsonData);
     }
    

    *业务层实现
    *

    public JsonData add(String cust_name, String cust_company, String cust_position, Stri
     int i = customerDao.add(cust_name,cust_company,cust_position,cust_phone,cust_
     if(i>0){
     return JsonData.buildSuc(null);
     }
     return JsonData.buildError("新增失败");
     }
    

    dao的实现

    public int add(String cust_name, String cust_company, String cust_position, String cu
     String sql = "insert into `t_customer`( `cust_name`, `cust_company`, `cust_po
     String createTime = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
     String modifyTime = createTime;
     return super.insert(sql, cust_name,cust_company,cust_position,cust_phone,cust
     }
    

    4.更新的实现

    **4.1前台页面
    **在这里插入图片描述
    4.2更新后台代码实现
    *Servlet *

    protected void update(HttpServletRequest req, HttpServletResponse resp) throws Servl
     String id = req.getParameter("id"); //当前客户id
     String cust_name = req.getParameter("cust_name");
     String cust_company = req.getParameter("cust_company");
     String cust_position = req.getParameter("cust_position");
     String cust_phone = req.getParameter("cust_phone");
     String cust_birth = req.getParameter("cust_birth");
     String cust_sex = req.getParameter("cust_sex");
     String cust_desc = req.getParameter("cust_desc");
     JsonData jsonData = customerService.update(cust_name,cust_company,cust_positi
     PrintJsonData.printJson(resp,jsonData);
     }
    

    service

    public JsonData update(String cust_name, String cust_company, String cust_position, S
     boolean i = customerDao.update(cust_name,cust_company,cust_position,cust_phon
     if(i){
     return JsonData.buildError("修改失败");
     }
     return JsonData.buildSuc(null);
     }
    

    dao

    public boolean update(String cust_name, String cust_company, String cust_position, St
     String sql = "UPDATE `t_customer` SET `cust_name` = ?, `cust_company` = ?, `
     String modifyTime = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
     return super.update(sql, cust_name,cust_company,cust_position,cust_phone,cust
     }
    

    5.添加拜访记录

    拜访记录是当前用户对该用户下面的客户发起的拜访记录信息
    5.1 创建拜访记录表(和用户表/客户表是 多对一关系)
    5.2前台
    在这里插入图片描述
    5.3后台实现
    *customerservlet , 需要创建对应的 拜访业务层 ,持久层对象和方法
    *

     protected void addVisit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
    
            String id = req.getParameter("id");
            因为客户名称 已经回显到了 弹出框,不需要获取
            String visit_time = req.getParameter("visit_time");
            String visit_desc = req.getParameter("visit_desc");
    
            //获取session中user 拜访的时候,是当前登录用户发起的拜访
            User user= (User) req.getSession().getAttribute("user");
    
            VisitService visitService = new VisitServiceImp();
            JsonData jsonData =  visitService.addVisit(id,visit_time,visit_desc,user.getId());
            PrintJsonData.print(resp,jsonData);
    
        }
    
    

    *customerservice
    *

    public JsonData addVisit(Integer id, String custId, String visitTime, String visitDes
     int i = visitDao.addVisit(id,custId,visitTime,visitDesc);
     if(i>0){
     return JsonData.buildSuc(null);
     }
     return JsonData.buildError("添加拜访记录失败");
     }
    

    customerdao

    public int addVisit(Integer id, String custId, String visitTime, String visitDesc) {
     //创建时间默认是当前时间
     String sql = "insert into t_visit(user_id,cust_id,visit_time,visit_desc,creat
     String creatTime = DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss");
     int insert = super.insert(sql, id, custId, visitTime, visitDesc, creatTime);
     return insert;
     }
    
    展开全文
  • Layui添加千位分割符有2种实现方法 1. js方法格式化数字,加入千分符,可以指定小数点;位数正负数均可,可以控制小数位数! 核心代码如下: <script type="text/html" id="amountM">{{number(d.amountM)}}</...

    Layui添加千位分割符有2种实现方法

    1. js方法格式化数字,加入千分符,可以指定小数点;位数正负数均可,可以控制小数位数!

    核心代码如下:

    <script type="text/html" id="amountM">{{number(d.amountM)}}</script>
    <script type="text/html" id="amountY">{{number(d.amountY)}}</script>
    <script>
     function number(s, n) {
            if (s !== null && s !== undefined  && s !== '') {
    
                n = n >= 0 && n <= 20 ? n : 2;
                s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
                var l = s.split(".")[0].split("").reverse(),
                    r = s.split(".")[1];
                r = r == null ? "" : "." + r;
                var t = "";
                // console.log(l)
                if (l[l.length - 1] === '-') {//负数不需要分隔号,
    
                    for (var i = 0; i < l.length; i++) {
                        if (l[i]==='-') {
                            t += l[i]+""
                            continue
                        }
                        //不是数组的倒数第二个元素才加"," ["0", "4", "5", "-"]
                        t += l[i] + ((i + 1) % 3 == 0 && i + 1 != l.length-1 ? "," : "");
    
                        //i + 1 != l.length会变成-,540.00,因为在5时元素位置2+1为3非数组长度
                        //t += l[i] + ((i + 1) % 3 == 0 && i + 1 != l.length ? "," : "");
                    }
                }
                else {
                    for (var i = 0; i < l.length; i++) {
                        t += l[i] + ((i + 1) % 3 == 0 && i + 1 != l.length ? "," : "");
                    }
                }
                return (
                    t.split("").reverse().join("") + r  //r 为小数部分
                );
            }else{
                return ''
            }
        }
    
        //获取token
      var token = CoreUtil.getData("access_token");
      //地址栏转义token中的#号
      var tokenQuery = token.replace("#", "%23");
      var tableIns1;
      var table = layui.table;
      var form = layui.form;
      var layer = layui.layer;
      var $ = jQuery = layui.jquery;
      var laydate = layui.laydate;
      var startTime = null;
      var endTime = null;
    
    
      layui.use(['table', 'layer', 'laydate'], function () {
    
        //加载table
        tableIns1 = table.render({
          elem: '#showTable'
          , contentType: 'application/json'
          , headers: {"authorization": token}
          , page: true //开启分页
          , url: '/productData/listByPage' //数据接口
          , method: 'POST'
          , parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
            return {
              "code": res.code, //解析接口状态
              "msg": res.msg, //解析提示文本
              "count": CoreUtil.isEmpty(res.data) ? 0 : res.data.total, //解析数据长度
              "data": CoreUtil.isEmpty(res.data) ? null : res.data.records //解析数据列表
            }
          }
          , cols: [
            [
              {type: 'checkbox', fixed: 'left'},
              // {field: 'acno', title: '流水编码', sort: true},
              // {field: 'codeCompany', title: '公司编码', sort: true},
                {field: 'period', title: '账期', sort: true},
                {field: 'company', title: '公司', sort: true},
                {field: 'cargoclass', title: '货类', sort: true},
              // {field: 'codePeriod', title: '账期编码', sort: true},
              // {field: 'codeClient', title: '客户编码', sort: true},
              {field: 'client', title: '客户', sort: true},
              // {field: 'codeCargo', title: '货物编码', sort: true},
              {field: 'cargo', title: '货物', sort: true},
              // {field: 'codeFchargetype', title: '费项编码', sort: true},
              // {field: 'fchargetype', title: '收费项目', sort: true},
              {field: 'amountM', title: '当月生产量',templet:'#amountM',sort: true},
              {field: 'amountY', title: '年度累计生产量',templet:'#amountY', sort: true},
              // {field: 'rtno', title: '预估费率编码', sort: true},
              // {field: 'rate', title: '预估费率', sort: true},
              // {field: 'incomeMY', title: '当月预估收入', sort: true},
              // {field: 'incomeYY', title: '年度累计预估收入', sort: true},
              // {field: 'incomeMR', title: '当月入账收入', sort: true},
              // {field: 'incomeYR', title: '年度累计入账收入', sort: true},
              // {field: 'incomeMW', title: '当月未入账收入', sort: true},
              // {field: 'incomeYW', title: '年度累计未入账收入', sort: true},
              // {field: 'codeCreatetype', title: '数据采集方式编码', sort: true},
              {field: 'createtype', title: '数据采集方式', sort: true},
              // {field: 'remark', title: '备注', sort: true},
              // {field: 'createtime', title: '创建时间', sort: true},
              // {field: 'creator', title: '创建人', sort: true},
              // {field: 'creatorname', title: '创建人', sort: true},
              // {field: 'modifytime', title: '修改时间', sort: true},
              // {field: 'modifier', title: '修改人', sort: true},
              // {field: 'modifiername', title: '修改人', sort: true},
              // {field: 'markDelete', title: '删除标志', sort: true},
              // {field: 'deletetime', title: '删除时间', sort: true},
              // {field: 'deleter', title: '删除人', sort: true},
              // {field: 'deletername', title: '删除人', sort: true},
              // {field: 'markDeclare', title: '申报标志', sort: true},
              // {field: 'declaretime', title: '申报时间', sort: true},
              // {field: 'declarer', title: '申报人', sort: true},
              // {field: 'declarername', title: '申报人', sort: true},
              // {field: 'markAudit', title: '审批标志', sort: true},
              // {field: 'audittime', title: '审批时间', sort: true},
              // {field: 'auditor', title: '审批人', sort: true},
              // {field: 'auditorname', title: '审批人', sort: true},
              // {field: 'markEnd', title: '扎帐标志', sort: true},
              // {field: 'endtime', title: '扎帐时间', sort: true},
              // {field: 'endder', title: '扎帐人', sort: true},
              // {field: 'enddername', title: '扎帐人', sort: true},
              {width: 120, toolbar: "#tool", title: '操作'}
            ]
          ]
          , toolbar: '#toolbar'
        });
    </script>
    

    效果图如下:
    在这里插入图片描述

    1. 判断数字是否为非负数,如果是正数,添加千位符
    <script type="text/html" id="amountM">{{fixed(d.amountM)}}</script>
    <script type="text/html" id="amountY">{{fixed(d.amountY)}}</script>
    //id 在对应的field中加: templet:'#对应id'
    <script>
      function fixed(str){
        if (str !== '' && str != null){
          if(str === 0){  //当为0时,不用处理
            return 0 ;
          }else {
            return str.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
          }
        } else {
          return '';
        }
      }
          //获取token
      var token = CoreUtil.getData("access_token");
      //地址栏转义token中的#号
      var tokenQuery = token.replace("#", "%23");
      var tableIns1;
      var table = layui.table;
      var form = layui.form;
      var layer = layui.layer;
      var $ = jQuery = layui.jquery;
      var laydate = layui.laydate;
      var startTime = null;
      var endTime = null;
    
    
      layui.use(['table', 'layer', 'laydate'], function () {
    
        //加载table
        tableIns1 = table.render({
          elem: '#showTable'
          , contentType: 'application/json'
          , headers: {"authorization": token}
          , page: true //开启分页
          , url: '/productData/listByPage' //数据接口
          , method: 'POST'
          , parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
            return {
              "code": res.code, //解析接口状态
              "msg": res.msg, //解析提示文本
              "count": CoreUtil.isEmpty(res.data) ? 0 : res.data.total, //解析数据长度
              "data": CoreUtil.isEmpty(res.data) ? null : res.data.records //解析数据列表
            }
          }
          , cols: [
            [
              {type: 'checkbox', fixed: 'left'},
              // {field: 'acno', title: '流水编码', sort: true},
              // {field: 'codeCompany', title: '公司编码', sort: true},
                {field: 'period', title: '账期', sort: true},
                {field: 'company', title: '公司', sort: true},
                {field: 'cargoclass', title: '货类', sort: true},
              // {field: 'codePeriod', title: '账期编码', sort: true},
              // {field: 'codeClient', title: '客户编码', sort: true},
              {field: 'client', title: '客户', sort: true},
              // {field: 'codeCargo', title: '货物编码', sort: true},
              {field: 'cargo', title: '货物', sort: true},
              // {field: 'codeFchargetype', title: '费项编码', sort: true},
              // {field: 'fchargetype', title: '收费项目', sort: true},
              {field: 'amountM', title: '当月生产量',templet:'#amountM',sort: true},
              {field: 'amountY', title: '年度累计生产量',templet:'#amountY', sort: true},
              // {field: 'rtno', title: '预估费率编码', sort: true},
              // {field: 'rate', title: '预估费率', sort: true},
              // {field: 'incomeMY', title: '当月预估收入', sort: true},
              // {field: 'incomeYY', title: '年度累计预估收入', sort: true},
              // {field: 'incomeMR', title: '当月入账收入', sort: true},
              // {field: 'incomeYR', title: '年度累计入账收入', sort: true},
              // {field: 'incomeMW', title: '当月未入账收入', sort: true},
              // {field: 'incomeYW', title: '年度累计未入账收入', sort: true},
              // {field: 'codeCreatetype', title: '数据采集方式编码', sort: true},
              {field: 'createtype', title: '数据采集方式', sort: true},
              // {field: 'remark', title: '备注', sort: true},
              // {field: 'createtime', title: '创建时间', sort: true},
              // {field: 'creator', title: '创建人', sort: true},
              // {field: 'creatorname', title: '创建人', sort: true},
              // {field: 'modifytime', title: '修改时间', sort: true},
              // {field: 'modifier', title: '修改人', sort: true},
              // {field: 'modifiername', title: '修改人', sort: true},
              // {field: 'markDelete', title: '删除标志', sort: true},
              // {field: 'deletetime', title: '删除时间', sort: true},
              // {field: 'deleter', title: '删除人', sort: true},
              // {field: 'deletername', title: '删除人', sort: true},
              // {field: 'markDeclare', title: '申报标志', sort: true},
              // {field: 'declaretime', title: '申报时间', sort: true},
              // {field: 'declarer', title: '申报人', sort: true},
              // {field: 'declarername', title: '申报人', sort: true},
              // {field: 'markAudit', title: '审批标志', sort: true},
              // {field: 'audittime', title: '审批时间', sort: true},
              // {field: 'auditor', title: '审批人', sort: true},
              // {field: 'auditorname', title: '审批人', sort: true},
              // {field: 'markEnd', title: '扎帐标志', sort: true},
              // {field: 'endtime', title: '扎帐时间', sort: true},
              // {field: 'endder', title: '扎帐人', sort: true},
              // {field: 'enddername', title: '扎帐人', sort: true},
              {width: 120, toolbar: "#tool", title: '操作'}
            ]
          ]
          , toolbar: '#toolbar'
        });
    </script>
    
    展开全文
  • ajax获取json来拼接layui的导航列表

    千次阅读 2018-04-29 19:22:37
    想写一个layUI的三级列表。现在来记录下。总的json格式[{"id":1,"level":0,"pid":0,"catename":"库存管理","alink":"stock/index","...

    想写一个layUI的三级列表。现在来记录下。

    总的json格式

    [{"id":1,"level":0,"pid":0,"catename":"库存管理","alink":"stock/index","sort":2,"status":true},{"id":2,"level":0,"pid":0,"catename":"个人办公","alink":"office/index","sort":0,"status":true},{"id":3,"level":0,"pid":0,"catename":"客户管理","alink":"Cust/index","sort":3,"status":true},{"id":4,"level":0,"pid":0,"catename":"人事管理","alink":"hr/index","sort":4,"status":true}'

    想要改造成这样的。

    [{  
        "title" : "后台首页",  
        "icon" : "icon-computer",  
        "href" : "page/main.html",  
        "spread" : false  
    },{  
        "title" : "二级菜单演示",  
        "icon" : "&#xe61c;",  
        "href" : "",  
        "spread" : false,  
        "children" : [  
            {  
                "title" : "二级菜单1",  
                "icon" : "&#xe631;",  
                "href" : "",  
                "spread" : false  
            },  
            {  
                "title" : "二级菜单2",  
                "icon" : "&#xe631;",  
                "href" : "",  
                "spread" : false  
            }  
        ]  
    }] 

    经过网上的参考。弄了两个Pojo来获得参数

    public class TitleResult {
        private List<?> data;
    
        public List<?> getData() {
            return data;
        }
    
        public void setData(List<?> data) {
            this.data = data;
        }
    }
    这个是总的
    public class TitleNode {
        private Integer id;
        private String title;
        private String icon;
        private String link;
        private Boolean status;
        private List<?> titleNode;

    这个是用来接收里面的data数据

    通过查询pid为0的数据可以获得最外层的数据

    在这里我使用了递归。

    private List<?> getTitleList(int parentId){
        XyMenuExample menuExample=new XyMenuExample();
        XyMenuExample.Criteria criteria= menuExample.createCriteria();
        criteria.andPidEqualTo(parentId);
    
        List<XyMenu> list= menuMapper.selectByExample(menuExample);
        List<TitleNode> resultList=new ArrayList<TitleNode>();
        for (XyMenu menu:list){
            TitleNode titleNode=new TitleNode();
            titleNode.setTitle(menu.getCatename());
            titleNode.setLink(menu.getAlink());
            titleNode.setStatus(menu.getStatus());
            titleNode.setId(menu.getId());
            titleNode.setTitleNode(getTitleList(menu.getId()));
            resultList.add(titleNode);
        }
        return resultList;
    }

    通过传进来的 parentId 不断的去遍历

    最后勉强的得到了想要的数据结构

    下面这段代码是我用来拼接导航的html的

    var html='';
    //获取菜单
    $.ajax({
        url:"/get/root" ,
        type:"post",
        dataType:"json",
        data:{},
        success:function (data) {
            var navs=data.data;
            html+='<ul class="layui-nav layui-nav-tree"  lay-filter="test">';
            $.each(navs,function (i,item) {
                html=html+'<li class="layui-nav-item">';
                html += '<a href="javascript:;" data-url="'+item.link+'" nav-id="'+item.id+'">' +
                    '<cite>'+item.title+'</cite></a>';
                if(item.titleNode!=""&& item.titleNode.length>0){
                    html += '<dl class="layui-nav-child">';
                    $.each(item.titleNode,function (j,item2) {
                        html+='<dd>'
                        html += '<a href="javascript:;" data-url="'+item2.link+'" ' +
                            'nav-id="'+item2.id+'">' +
                            '<cite>'+item2.title+'</cite></a>';
                        if(item2.titleNode!=""&&item2.titleNode.length>0){
                            html += '<ol class="layui-nav-child">';
                            $.each(item2.titleNode,function (k,item3) {
                                html += '<li>'+
                                    '<a href="javascript:;" data-url="'+item3.link+'" nav-id="'+item3.id+'">'+
                                    '<cite>'+item3.title+'</cite>'+
                                    '</a>'+
                                    '</li>';
                            });
                            html+= '</ol>';
                        }
                    });
                    html+= '</dl>' ;
                }
                html+= '</li>';
            });
            html+='</ul>';
           // $('#admin-navbar-side').html(html);
        }
    但是最后结果不是很理想

    第一层的数据出来了。查看页面元素。二、三层的数据也有 。但是效果没有了。 

    先记录这。容我这个小菜鸟研究下。如果有大佬知道 请告知。

    在度娘这里找到了问题的解决方法

    http://blog.sina.com.cn/s/blog_667ac0360102xbgw.html 

    我先试下

    OK了  在添加了html 片段后 加入这句话用来更新所有element的元素

    element.init();
    截图留念



    展开全文
  • 1、pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=...

    1、pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>com.fy</groupId>
        <artifactId>openplatform</artifactId>
        <version>1.0-SNAPSHOT</version>
        <packaging>war</packaging>
    
        <!-- 编码与版本确定 -->
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <maven.compiler.source>1.8</maven.compiler.source>
            <maven.compiler.target>1.8</maven.compiler.target>
            <springframework.version>5.1.6.RELEASE</springframework.version>
            <quartz.version>2.2.3</quartz.version>
        </properties>
    
        <dependencies>
    
            <!-- web项目的编译环境 -->
            <dependency>
                <!-- jstl 支持 -->
                <groupId>javax.servlet</groupId>
                <artifactId>jstl</artifactId>
                <version>1.2</version>
                <scope>compile</scope>
            </dependency>
            <dependency>
                <!-- servlet编译环境 -->
                <groupId>javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
                <version>3.1.0</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <!-- jsp编译环境 -->
                <groupId>javax.servlet</groupId>
                <artifactId>jsp-api</artifactId>
                <version>2.0</version>
                <scope>provided</scope>
            </dependency>
    
            <!-- 单元测试 -->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
                <scope>test</scope>
            </dependency>
    
            <!-- 数据库相关 -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.47</version>
            </dependency>
            <!-- 连接池 -->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>1.1.12</version>
            </dependency>
            <!-- 分页插件 -->
            <dependency>
                <groupId>com.github.pagehelper</groupId>
                <artifactId>pagehelper</artifactId>
                <version>5.1.10</version>
            </dependency>
    
            <!-- 阿里巴巴FastJson -->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>1.2.54</version>
            </dependency>
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>2.9.8</version>
            </dependency>
    
            <!-- Spring框架相关 -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>5.1.6.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aspects</artifactId>
                <version>5.1.6.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-test</artifactId>
                <version>5.1.6.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>5.1.6.RELEASE</version>
            </dependency>
            <!-- Spring整合mybatis -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>1.3.1</version>
            </dependency>
            <!-- MyBatis -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.4.5</version>
            </dependency>
            <!-- springMVC -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>5.1.6.RELEASE</version>
            </dependency>
            <!-- Quartz相关 -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context-support</artifactId>
                <version>${springframework.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-tx</artifactId>
                <version>${springframework.version}</version>
            </dependency>
            <dependency>
                <groupId>org.quartz-scheduler</groupId>
                <artifactId>quartz</artifactId>
                <version>${quartz.version}</version>
            </dependency>
        </dependencies>
    
    
        <build>
            <!-- 更改maven编译规则 -->
            <resources>
                <resource>
                    <!-- 资源目录 -->
                    <directory>src/main/java</directory>
                    <includes>
                        <include>*.xml</include><!-- 默认(新添加自定义则失效) -->
                        <include>**/*.xml</include><!-- 新添加 */代表1级目录 **/代表多级目录 -->
                    </includes>
                    <filtering>true</filtering>
                </resource>
            </resources>
        </build>
    
    </project>
    

    2、Spring-Context.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <!--
      dtd: xxx.dtd     document type definition
      xsd: xxx.xsd     xml  schema definition
     -->
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xmlns:tx="http://www.springframework.org/schema/tx"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
                               http://www.springframework.org/schema/beans/spring-beans.xsd
                               http://www.springframework.org/schema/aop
                               http://www.springframework.org/schema/aop/spring-aop.xsd
                               http://www.springframework.org/schema/tx
                               http://www.springframework.org/schema/tx/spring-tx.xsd
                               http://www.springframework.org/schema/context
                               http://www.springframework.org/schema/context/spring-context.xsd">
    
    
        <!-- DataSource -->
        <context:property-placeholder location="classpath:jdbc.properties"/>
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
            <!--基本配置-->
            <property name="driverClassName" value="${jdbc.driverClass}"/>
            <property name="url" value="${jdbc.url}"/>
            <property name="username" value="${jdbc.username}"/>
            <property name="password" value="${jdbc.password}"/>
    
            <!-- 配置初始化大小、最小、最大 -->
            <property name="initialSize" value="${jdbc.init}"/>
            <property name="minIdle" value="${jdbc.minIdle}"/>
            <property name="maxActive" value="${jdbc.maxActive}"/>
    
            <!-- 配置获取连接等待超时的时间 ms-->
            <property name="maxWait" value="60000"/>
    
            <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
            <property name="timeBetweenEvictionRunsMillis" value="60000"/>
    
            <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
            <property name="minEvictableIdleTimeMillis" value="300000"/>
        </bean>
        <!-- SqlSessionFactory -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <!-- 注入连接池 -->
            <property name="dataSource" ref="dataSource"></property>
            <!-- 注入dao-mapper文件信息 ,如果映射文件和dao接口 同包且同名,则此配置可省略-->
            <property name="mapperLocations">
                <list>
                    <value>classpath:com/fy/dao/*.xml</value>
                </list>
            </property>
            <!-- 为 dao-mapper文件中的实体 定义缺省包路径
                如:<select id="queryAll" resultType="User"> 中 User类可以不定义包
            -->
            <property name="typeAliasesPackage" value="com.fy.entity"></property>
    
            <property name="plugins">
                <array>
                    <bean class="com.github.pagehelper.PageInterceptor">
                        <property name="properties">
                            <props>
                                <!-- 页号 调整到合理的值  0  max -->
                                <prop key="reasonable">true</prop>
                            </props>
                        </property>
                    </bean>
                </array>
            </property>
        </bean>
    
        <!-- DAO  MapperScannerConfigurer -->
        <bean id="mapperScannerConfigurer9" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <!-- dao接口所在的包  如果有多个包,可以用逗号或分号分隔
               <property name="basePackage" value="com.a.dao,com.b.dao"></property>
            -->
            <property name="basePackage" value="com.fy.dao"></property>
            <!-- 如果工厂中只有一个SqlSessionFactory的bean,此配置可省略 -->
            <!--<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>-->
        </bean>
        <!-- 扫描包,并排除Controller -->
        <context:component-scan base-package="com.fy" use-default-filters="true">
            <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        </context:component-scan>
        <!-- 引入一个事务管理器,其中依赖DataSource,借以获得连接,进而控制事务逻辑 -->
        <bean id="tx" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource"></property>
        </bean>
        <!-- @Transactional -->
        <tx:annotation-driven transaction-manager="tx"/>
    </beans>
    

    3、mvc.xml

    <beans 	xmlns="http://www.springframework.org/schema/beans"
              xmlns:context="http://www.springframework.org/schema/context"
              xmlns:mvc="http://www.springframework.org/schema/mvc"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://www.springframework.org/schema/beans
    							http://www.springframework.org/schema/beans/spring-beans.xsd
    							http://www.springframework.org/schema/context
    							http://www.springframework.org/schema/context/spring-context.xsd
    							http://www.springframework.org/schema/mvc
    							http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    
        <!-- 注解扫描 -->
        <context:component-scan base-package="com.fy" use-default-filters="false">
            <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        </context:component-scan>
    
        <!-- 注解驱动 -->
        <mvc:annotation-driven>
            <!-- 安装FastJson,转换器 -->
            <mvc:message-converters>
                <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                    <!-- 声明转换类型:json -->
                    <property name="supportedMediaTypes">
                        <list>
                            <value>application/json</value>
                        </list>
                    </property>
                </bean>
            </mvc:message-converters>
        </mvc:annotation-driven>
    
        <!-- 视图解析器
    	     作用:1.捕获后端控制器的返回值="hello"
    	          2.解析: 在返回值的前后 拼接 ==> "/hello.jsp"
    	 -->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <!-- 前缀 -->
            <property name="prefix" value="/"></property>
            <!-- 后缀 -->
            <property name="suffix" value=".jsp"></property>
        </bean>
    
        <!--
           额外的增加一个handler,且其requestMapping:  "/**" 可以匹配所有请求,但是优先级最低
          所以如果其他所有的handler都匹配不上,请求会转向 "/**" ,恰好,这个handler就是处理静态资源的
          处理方式:将请求转会到tomcat中名为default的Servlet
    
          RequestMapping  /*   /a   /b  /c   /dxxxx    /a/b
                          /**
         -->
        <mvc:default-servlet-handler/>
    </beans>
    

    4、web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
             version="4.0">
    
        <!-- SpringMVC前端(核心)控制器
             1. 前端,接收所有请求
             2. 启动SpringMVC工厂  mvc.xml
             3. springMVC流程调度
        -->
        <servlet>
            <servlet-name>minamoto</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:mvc.xml</param-value>
            </init-param>
            <!-- 懒 饿  可选-->
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>minamoto</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
    
        <!-- 此过滤器会进行:request.setCharactorEncoding("utf-8"); -->
        <filter>
            <filter-name>encoding</filter-name>
            <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
            <init-param>
                <param-name>encoding</param-name>
                <param-value>utf-8</param-value>
            </init-param>
        </filter>
        <filter-mapping>
            <filter-name>encoding</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    
        <!--启动Spring工厂 -->
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </context-param>
    </web-app>
    

    5、jdbc.properties

    jdbc.driverClass=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/oa3_sys?useUnicode=true&characterEncoding=UTF-8&useSSL=false
    jdbc.username=root
    jdbc.password=root
    jdbc.init=1
    jdbc.minIdle=1
    jdbc.maxActive=3
    

    6、实体类

    public class Custom {
        private int id;
        private String username;
        private String password;
        private String nickname;
        private String address;
        private int money;
        private int state = -1;
    

    7、DAO接口与mapper.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <mapper namespace="com.fy.dao.CustomDao">
        <select id="selectCustom" resultType="Custom">
            SELECT id, username, password, nickname, address, money, state
            FROM oa_custom
            <where>
                <if test="username != null"> username like concat('%',#{username},'%')  </if>
                <if test="state != -1"> and state = #{state} </if>
            </where>
            order by id
        </select>
        <select id="selectCustom2" resultType="Custom">
            SELECT id, username, password, nickname, address, money, state
            FROM oa_custom
            order by id
            limit #{arg0} , #{arg1}
        </select>
        
        <insert id="insertCustom" parameterType="Custom">
            insert into oa_custom (username, password, nickname, address, money, state)
            value (#{username}, #{password}, #{nickname}, #{address}, #{money}, #{state})
        </insert>
    
        <update id="updateCustom" parameterType="Custom">
            update oa_custom
            set username = #{username}, password = #{password},
             nickname = #{nickname}, address = #{address}, money = #{money}, state = #{state}
            where id = #{id}
        </update>
    
        <delete id="deleteCustom" parameterType="Integer">
            delete from oa_custom
            where id = #{id}
        </delete>
    
        <delete id="deleteCustom2" parameterType="Integer">
            delete from oa_custom
            where id in
            <foreach collection="array" open="(" separator="," close=")" item="ids" index="i">
                #{ids}
            </foreach>
        </delete>
        
    </mapper>
    

    8、Service接口与实现

    public interface CustomService {
    
        /** 基础CURD */
        PageInfo<Custom> selectCustom(Custom custom, Page page);
        Integer insertCustom(Custom custom);
        Integer updateCustom(Custom custom);
        Integer deleteCustom(Integer id);
        Integer deleteCustom2(Integer[] ids);
    }
    
    package com.fy.service;
    
    import com.fy.dao.CustomDao;
    import com.fy.entity.Custom;
    import com.fy.entityutil.Page;
    import com.github.pagehelper.PageHelper;
    import com.github.pagehelper.PageInfo;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    
    import java.util.List;
    
    /**
     * shigen.kyo 2020/9/7 14:40
     * 凌空一跃,骑士飞踢!
     */
    @Service
    @Transactional
    public class CustomServiceImpl implements CustomService {
    
        @Autowired
        private CustomDao customDao;
    
        @Override
        public PageInfo<Custom> selectCustom(Custom custom, Page page) {
            PageHelper.startPage(page.getCurrPage(), page.getPageSize());
            List<Custom> customs = customDao.selectCustom(custom);
            PageInfo<Custom> pageInfo = new PageInfo<>(customs);
            return pageInfo;
        }
    
        @Override
        public Integer insertCustom(Custom custom) {
            Integer integer = customDao.insertCustom(custom);
            return integer;
        }
    
        @Override
        public Integer updateCustom(Custom custom) {
            Integer integer = customDao.updateCustom(custom);
            return integer;
        }
    
        @Override
        public Integer deleteCustom(Integer id) {
            System.out.println("");
            return null;
        }
    
        @Override
        public Integer deleteCustom2(Integer[] ids) {
            Integer integer = customDao.deleteCustom2(ids);
            return integer;
        }
    }
    
    

    9、Controller

    package com.fy.controller;
    
    import com.fy.entity.Custom;
    import com.fy.entityutil.AjaxMessage;
    import com.fy.entityutil.Page;
    import com.fy.entityutil.TableData;
    import com.fy.service.CustomService;
    import com.github.pagehelper.PageInfo;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    /**
     * shigen.kyo 2020/9/7 14:40
     * 凌空一跃,骑士飞踢!
     */
    @Controller
    @RequestMapping("/custom")
    public class CustomController {
    
        @Autowired
        @Qualifier("customServiceImpl")
        private CustomService customService;
    
        @ResponseBody
        @RequestMapping("/selectCustom")
        public TableData selectCustom(Custom custom, int page, int limit) {
            System.out.println(custom);
            // 获取分页信息
            Page pageBean = new Page(page, limit);
            // 查的业务
            PageInfo<Custom> pageInfo = customService.selectCustom(custom, pageBean);
    
            // 生成前端用的东西
            TableData tableData = new TableData();
    
            tableData.setCode(0);
            tableData.setMsg("成功");
            tableData.setCount(pageInfo.getTotal());
            tableData.setData(pageInfo.getList());
    
            return tableData;
        }
    
        @RequestMapping("/del")
        @ResponseBody
        public AjaxMessage delCustom2(Integer[] ids) {
            System.out.println(ids.toString());
            Integer integer = customService.deleteCustom2(ids);
            if (integer != null && integer != 0) {
                return new AjaxMessage(true, "删除成功");
            }
            return new AjaxMessage(false, "删除失败");
        }
    
        @RequestMapping("/add")
        @ResponseBody
        public AjaxMessage addCustom(Custom custom) {
            System.out.println(custom.toString());
            Integer integer = customService.insertCustom(custom);
            if (integer != null && integer != 0) {
                return new AjaxMessage(true, "添加成功");
            }
            return new AjaxMessage(false, "添加失败");
        }
    
        @RequestMapping("/update")
        @ResponseBody
        public AjaxMessage updateCustom(Custom custom) {
            System.out.println(custom.toString());
            Integer integer = customService.updateCustom(custom);
            if (integer != null && integer != 0) {
                return new AjaxMessage(true, "更新成功");
            }
            return new AjaxMessage(false, "更新失败");
       }
    }
    
    

    10、前端客户管理界面

    
    <form action="#" class="layui-form" id="selectform">
        <div class="layui-form-item">
            <div class="layui-inline">
                <label>用户名:</label>
                <div class="layui-inline">
                    <input type="text" id="name" name="username" autocomplete="off" placeholder="请输入名称"
                           class="layui-input">
                </div>
                状态:
                <div class="layui-inline">
                    <select name="state" id="sstate">
                        <option value="-1">请选择</option>
                        <option value="0">无效</option>
                        <option value="1">有效</option>
                    </select>
                </div>
                <button class="layui-btn" lay-submit lay-filter="customer-table" id="gogo">搜索</button>
            </div>
        </div>
    </form>
    
    
    
    <table class="layui-hide" id="customer-table" lay-filter="customer-table"></table>
    
    <!-- 头部工具栏 -->
    <script type="text/html" id="toolbarDemo">
        <div class="layui-btn-container">
            <button class="layui-btn layui-btn-sm" lay-event="headadd">添加</button>
            <button class="layui-btn layui-btn-sm layui-btn-danger" lay-event="headdel">删除</button>
        </div>
    </script>
    
    <!-- 右侧工具栏 -->
    <script type="text/html" id="barDemo">
        <a class="layui-btn layui-btn-xs" lay-event="rightedit">编辑</a>
    </script>
    
    
    
    
    <script type="text/javascript" >
    
        layui.use(['table', 'layer', 'form',  'layedit', 'laydate'], function () {
    
            var table = layui.table;
            var layer = layui.layer;
            var form = layui.form
                , layer = layui.layer
                , layedit = layui.layedit
                , laydate = layui.laydate;
            form.render(); // 表单更新渲染
    
            table.render({
                elem: '#customer-table'
                , url: 'custom/selectCustom'
                , toolbar: '#toolbarDemo' //开启头部工具栏,并为其绑定左侧模板
                , cellMinWidth: 80 //全局定义常规单元格的最小宽度,layui 2.2.1 新增
                , page: { //支持传入 laypage 组件的所有参数(某些参数除外,如:jump/elem) - 详见文档
                    layout: ['prev', 'page', 'next', 'skip', 'limit', 'count'] //自定义分页布局
                    //,curr: 5 //设定初始在第 5 页
                    , groups: 5 //只显示 1 个连续页码
                    , first: false //不显示首页
                    , last: false //不显示尾页
                    , limit: 3
                    , limits: [2, 3, 5]
                    , defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义,去除该参数即可
                        title: '提示'
                        , layEvent: 'LAYTABLE_TIPS'
                        , icon: 'layui-icon-tips'
                    }]
                }
                , cols: [[
                    {type: 'checkbox', fixed: 'left'}
                    , {field: 'id', title: 'ID', sort: true}
                    , {field: 'username', title: '账号'}
                    , {field: 'nickname', title: '公司名称'}
                    , {field: 'money', title: '账户余额'}
                    , {field: 'address', title: '公司地址'}
                    , {field: 'state', title: '状态'}
                    , {field: 'password', title: '密码', hide:true}
                    , {
                        field: 'state', title: '状态', templet: function (data) {
                            return (data.state == 1) ?
                                '<span class="layui-badge layui-bg-green">有效</span>' :
                                '<span class="layui-badge layui-bg-red" >无效</span>'
                        }
                    }
                    , {field: 'right', title: '操作', toolbar: '#barDemo'}
                ]]
            });
    
            // 监听头部工具
            table.on('toolbar(customer-table)', function (obj) {
                switch (obj.event) {
                    case 'headadd':
                        openNewWindow(null);
                        break;
    
                    case 'headdel':
                        var data = table.checkStatus('customer-table').data;
                        if (data.length > 0) {
                            layer.confirm('真的要删除这一行吗', function (index) {
                                var param = ""
                                $.each(data, function (i, obj) { // 遍历拼接
                                    param += "&ids=" + obj.id
                                })
                                $.ajax({
                                    url: 'custom/del',
                                    data: param,
                                    method: 'get',
                                    success: function (result) {
                                        if (result.status) {
                                            table.reload('customer-table', {});
                                        } else {
                                            alert(result.message)
                                        };
                                        layer.close(index);
                                    }
                                })
                            })
                        }
                        break;
                }
            })
    
    
            // 监听行工具事件
            table.on('tool(customer-table)', function (obj) {
                var data = obj.data;
                switch (obj.event) {
                    case 'rightedit': {
                        openNewWindow(data);
                        break;
                    }
                }
            })
    
            function openNewWindow(data) {
    
                var datt = data;
    
                layer.open({
                    type: 1,
                    content: data == null ? $('#customer-add-layer').html() : $('#customer-edit-layer').html(),
                    title: '编辑',
                    area: ['500px', '400px'],
                    btn: ['提交', '取消'] , // 可以无限个按钮
                    yes:function (index, layero) {
                        // layer.load();
                        // form.on('submit(addRole)', function(datt) {
                            // console.log($("#customer-add-form").serialize());
                            // console.log($("#customer-edit-form").serialize());
                            console.log("data=" + datt);
                            $.ajax({
                                url: "custom/" + (data == null ? 'add' : 'update'),
                                // 序列化
                                data: data == null ? $("#customer-add-form").serialize() : $("#customer-edit-form").serialize(),
                                method: 'get',
                                type: JSON,
                                success: function (result) {
                                    if (result.status) {
                                        table.reload('customer-table', {});
                                    } else {
                                        alert(result.message)
                                    };
                                    layer.closeAll();
                                }
                            })
                        // });
    
                    },
                    success: function (layero, index) {
                        form.render();
                        // 添加form标识
                        layero.addClass('layui-form');
                        // 将保存按钮改变成提交按钮
                        layero.find('.layui-layer-btn0').attr({
                            'lay-filter' : 'addRole',
                            'lay-submit' : ''
                        });
    
                        if (data != null) {
                            // alert(data.state);
                            // form.val("cstomer-edit-form");
                            form.val("customer-edit-form", {
                                "id": data.id
                                ,"username": data.username
                                ,"nickname": data.nickname
                                ,"password": data.password
                                ,"address": data.address
                                ,"money": data.money
                                ,"state": data.state
                            });
                        }
                    }
                })
            }
    
    
            form.on('submit(customer-table)', function (data) {
                table.reload('customer-table', {
                    page: {curr: 1}, // 重新从第1页开始
                    where: data.field
                });
                return false; // 阻止表单跳转
            });
    
            //自定义验证规则
            form.verify({
                content: function(value){
                    layedit.sync(editIndex);
                }
            });
    
        });
    </script>
    
    
    <script type="text/html" id="customer-edit-layer">
        <form id="customer-edit-form" style="width: 80%" class="layui-form" lay-filter="customer-edit-form">
            <input type="hidden" name="id">
    
            <div class="layui-form-item">
                <label class="layui-form-label">用户名</label>
                <div class="layui-input-block">
                    <input type="text" name="username" lay-verify="required" placeholder="请输入用户名"
                           autocomplete="off"
                           class="layui-input">
                </div>
            </div>
    
            <div class="layui-form-item">
                <label class="layui-form-label">名称</label>
                <div class="layui-input-block">
                    <input type="text" name="nickname" lay-verify="required" placeholder="请输入公司名称"
                           autocomplete="off"
                           class="layui-input">
                </div>
            </div>
    
            <div class="layui-form-item">
                <label class="layui-form-label">密码</label>
                <div class="layui-input-block">
                    <input type="password" name="password" lay-verify="required" placeholder="请输入密码"
                           autocomplete="off"
                           class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">地址</label>
                <div class="layui-input-block">
                    <input type="text" name="address" lay-verify="required" placeholder="请输入地址"
                           autocomplete="off"
                           class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">账户金额()</label>
                <div class="layui-input-block">
                    <input type="number" name="money"  lay-verify="required" placeholder="请输入账号金额"
                           autocomplete="off"
                           class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">状态</label>
                <div class="layui-input-block">
                    <input type="radio" name="state" title="有效" value="1" checked/>
                    <input type="radio" name="state" title="无效" value="0"/>
                </div>
            </div>
        </form>
    </script>
    
    
    
    <script type="text/html" id="customer-add-layer">
        <form id="customer-add-form" style="width: 80%" class="layui-form" lay-filter="customer-add-form">
    
            <div class="layui-form-item">
                <label class="layui-form-label">用户名</label>
                <div class="layui-input-block">
                    <input type="text" name="username"  lay-verify="required" placeholder="请输入用户名"
                           autocomplete="off"
                           class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">名称</label>
                <div class="layui-input-block">
                    <input type="text" name="nickname"  lay-verify="required" placeholder="请输入公司名称"
                           autocomplete="off"
                           class="layui-input">
                </div>
            </div>
    
            <div class="layui-form-item">
                <label class="layui-form-label">密码</label>
                <div class="layui-input-block">
                    <input type="password" name="password"  lay-verify="required" placeholder="请输入密码"
                           autocomplete="off"
                           class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">地址</label>
                <div class="layui-input-block">
                    <input type="text" name="address"  lay-verify="required" placeholder="请输入地址"
                           autocomplete="off"
                           class="layui-input">
                </div>
            </div>
    
            <div class="layui-form-item">
                <label class="layui-form-label">账户金额()</label>
                <div class="layui-input-block">
                    <input type="number" name="money"  lay-verify="required" placeholder="请输入账号金额"
                           autocomplete="off"
                           class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">状态</label>
                <div class="layui-input-block">
                    <input type="radio" name="state" title="有效" value="1" checked/>
                    <input type="radio" name="state" title="无效" value="0"/>
                </div>
            </div>
        </form>
    </script>
    
    展开全文
  • layui分页

    2017-11-10 16:46:15
    使用的layui版本为:layui-v1.0.9,现在新版本已经2.X了有些属性改变了,如果你的版本是2.0以上请参照我的博客:《 layui完美分页,ajax请求分页(真分页) 【2.0版本】》 如果layui分页有的时候可以渲染,有的...
  • LayUI 实现分页

    2017-10-30 19:13:00
    <div class="admin-main"> <blockquote class="layui-elem-quote"> <form class="layui-form" action="" > <div class="layui-form-item"> ...
  • 【录播】客户列表(页面显示)(9分钟) 【录播】客户信息更新(后台代码)(7分钟) 【录播】更新客户信息(页面代码)(31分钟) 07 登录日志管理 【录播】模块开发简介(4分钟) 【录播】数据更新与插入(25分钟)...
  • 客户列表 <div class="layui-field-box layui-form"> <table class="layui-table admin-table" id="t_customerInfo"> java: @RequestMapping(value="layui_fys") @ResponseBody ...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 411
精华内容 164
关键字:

layui客户列表