欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

EasyUI(1)——综合案例(结合后台的CRUD)

程序员文章站 2022-03-05 09:30:35
...

公共部分代码

//弹出框默认应该是模态框
$.fn.dialog.defaults.modal = true;
//弹出框默认应该是关闭状态
$.fn.dialog.defaults.closed = true;
//默认验证信息
$.fn.textbox.defaults.missingMessage="请填写这一列";

Header.js

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<link rel="stylesheet" href="/static/click/font_click.css">
<!-- easyui的核心css -->
<link rel="stylesheet" id="easyuiTheme" href="/static/easyui/themes/default/easyui.css">
<!-- easyui的图标css -->
<link rel="stylesheet" href="/static/easyui/themes/icon.css">
<!-- easyui的颜色 -->
<link rel="stylesheet" href="/static/easyui/themes/color.css">
<!-- easyui扩展验证相关的css -->
<link rel="stylesheet" href="/static/easyui/validatebox/jeasyui.extensions.validatebox.css"  />
<!-- jquery的核心js -->
<script type="text/javascript" src="/static/easyui/jquery.min.js"></script>
<script type="text/javascript" src="/static/easyui/jquery.cookie.js"></script>
<!-- easyui的核心js -->
<script type="text/javascript" src="/static/easyui/jquery.easyui.min.js"></script>
<!-- 引入jquery的扩展js -->
<script type="text/javascript" src="/static/easyui/jquery.jdirk.js"></script>
<%--<script type="text/javascript" src="/static/easyui/jquery.edatagrid.js"></script>--%>
<!-- 汉化js -->
<script type="text/javascript" src="/static/easyui/locale/easyui-lang-zh_CN.js"></script>
<!-- 引入easyui验证相关的js -->
<script type="text/javascript" src="/static/easyui/validatebox/jeasyui.extensions.validatebox.rules.js"></script>

<link href="/static/ma3/css/player.css" rel="stylesheet" type="text/css" />

<script type="text/javascript" src="/static/easyui/jquery.cookie.js"></script>

主页面整体布局

<body class="easy
ui-layout">
    <div data-options="region:'north',split:true" style="height:100px;">
        头部信息(主要放的是logo,用户名等...)
    </div>
    <div data-options="region:'south',split:true" style="height:100px;">
        版权信息等内容
    </div>
    <div data-options="region:'west',title:'菜单信息',split:true" style="width:230px;">
        主要存放菜单信息(树菜单)
    </div>
    <div data-options="region:'center',title:'欢迎你啊!!!'" style="padding:5px;background:#eee;">
        主体内容(展示欢迎页面) -> layout中主体必需有
    </div>
</body>

左侧树菜单布局

h5:

<div data-options="region:'west'" title="菜单" style="width:200px;">
    <ul id="menu"></ul>
</div>

js:

$("#menu").tree({
    url:"/treeMenu",
    //动画
    animate:true,
    //定义是否显示树控件上的虚线
    lines:true,
    onClick:function(node){
    	//判断是否为二级菜单
        if(node.url){
        	//判断标签是否已在选项卡中打开
            if($("#tab").tabs("exists",node.text)){
            	//如果已存在则跳转
                $("#tab").tabs("select",node.text);
            }else {
            	//不存在则添加
                $("#tab").tabs("add",{
                    title:node.text,
                    content:"<iframe width='100%' height='100%' frameborder='0' src='"+node.url+"'/>",
                    closable:true
                });
            }
        }
    }
});

后台准备数据

service层

    public List<Menu>  findMenusByLoginUser() {
        //创建一个装一级菜单的集合
        List<Menu> parents = new ArrayList<>();
        //根据用户查询拥有的菜单(获取到的都是二级菜单)
        List<Menu> menus = menuRepository.findMenusByLoginUser(UserContext.getUserBySession());
        for (Menu menu : menus) {
            //获取到菜单的父菜单
            Menu parent = menu.getParent();
            //判断菜单是不是在装一级菜单的集合中
            if (!parents.contains(parent)){
                //如果不在 则放入到集合中
                parents.add(parent);
            }
            //将二级菜单放到一级菜单中
             parent.getChildren().add(menu);
        }
        return parents;
    }

@Query语句
@Query("select distinct o from Employee e join e.roles r join r.permissions p join p.menu o where e=?1")

员工管理

数据列表(通过HTML的方式加载数据)

<table id="dg" class="easyui-datagrid" data-options="
    fit:true,
    url:'/employee/datagrid',
    title:'员工列表',
    fitColumns:true,
    toolbar:'#tb',
    pagination:true,
    rownumbers:true
    ">
    <thead>
    <tr>
        <th data-options="field:'id',checkbox:true,width:'1%'">ID</th>
        <th data-options="field:'username',width:'14%',align:'center',sortable:true" editor="{type:'validatebox',options:{required:true}}">用户名</th>
        <th data-options="field:'password',width:'20%',align:'center'" editor="{type:'validatebox',options:{required:true}}">密码</th>
        <th data-options="field:'email',width:'20%',align:'center'" editor="{type:'validatebox',options:{required:true,validType:'email'}}">邮箱</th>
        <th data-options="field:'headImage',width:'15%',align:'center',formatter:formatterHeadImage">头像</th>
        <th data-options="field:'age',width:'10%',align:'center',sortable:true" editor="numberbox">年龄</th>
        <th data-options="field:'department',width:'20%',align:'center',formatter:formatterDept">部门</th>
    </tr>
    </thead>
</table>

部门和图片的格式化

/*图片格式化*/
function formatterHeadImage(v,r,i){
  return "<img alt='无图片' width='50' src='"+v+"' />";
}

/*显示部门*/
function formatterDept(v,r,i){
  if (v){
    return v.name;
  }
}

回收站数据(通过JS的方式加载数据)

html

<div id="re_Dlg" class="easyui-dialog" data-options="width:800,height:400,buttons:'#re_bb'">
    <form id="re_ff" method="post">
        <input type="hidden" name="id">
        <table cellpadding="5">
            <tr>
                <td colspan="4">
                    <div class="easyui-layout" data-options="width:800,height:400">
                        <div data-options="region:'center'">
                            <table id="re_datagrid"></table>
                        </div>
                    </div>
                </td>
            </tr>
        </table>
    </form>
</div>

js

 /*回收站js*/
  //获取对应的表格
  var re_datagrid = $("#re_datagrid");
  //弹出框对应的jquery对象
  var re_Dlg = $("#re_Dlg");
  //弹出框表单对应的对象
  var re_ff = $("#re_ff");


    /*创建回收站表 双击还原数据*/
  re_datagrid.datagrid({
    border:false,
    fit:true,
    fitColunms:true,
    url:'/employee/re_datagrid',
    pagination:true,
    rownumbers:true,
    showHeader:false,
    onDblClickRow : function (index,row,value) {
        console.debug(row.id)
        $.messager.confirm("提示","是否还原选中的数据",function (inf) {
            if (inf){
                $.get("/employee/update_status",{id:row.id},function (res) {
                    if (res.success){
                        $("#dg").datagrid("reload");
                        $("#re_datagrid").datagrid("reload");
                    }else {
                        $.messager.alert("错误", res.msg, "error");
                    }
                })
            }
        })
    },

    columns :[[
      {field :'id',title:'名称',width :'6%',align :'center',checkbox:true},
      {field:'username',title:'用户名',width:'14%',align:'center'},
      {field:'password',title:'密码',width:'20%',align:'center'},
      {field:'email',title:'邮件',width:'15%',align:'center'},
      {field:'headImage',title:'头像',width:'15%',align:'center',formatter:formatterHeadImage},
      {field:'age',title:'年龄',width:'10%',align:'center'},
      {field:'department',title:'部门',width:'20%',align:'center',formatter:formatterDept}
    ]]
  });

添加按钮与事件

准备按钮

<div id="tb" style="padding:5px;height:auto">
    <div style="margin:5px">
        <shiro:hasPermission name="employee:save">
            <a href="javascript:void(0);" data-method="add" class="easyui-linkbutton" iconCls="icon-add" plain="true">添加</a>
        </shiro:hasPermission>
        <shiro:hasPermission name="employee:update">
            <a href="javascript:void(0);" data-method="edit" class="easyui-linkbutton" iconCls="icon-edit" plain="true">修改</a>
        </shiro:hasPermission>
        <shiro:hasPermission name="employee:delete">
            <a href="javascript:void(0);" data-method="remove" class="easyui-linkbutton" iconCls="icon-remove" plain="true">删除</a>
        </shiro:hasPermission>
        <a href="javascript:void(0);" data-method="reset" class="easyui-linkbutton" iconCls="icon-reload" plain="true">重置</a>

        <a href="javascript:void(0);" data-method="recycle" class="easyui-linkbutton" iconCls="icon-back" plain="true">回收站</a>
    </div>
    //高级查询
    <div style=" position: fixed ! important; right: 10px; top: 40px;">
        <form id="searchForm" method="post" action="/employee/download">
            用户名:<input class="easyui-textbox" type="text" name="username"/>
            邮箱:<input class="easyui-textbox" type="text" name="email"/>
                部门: <input class="easyui-combobox" name="deptId"
                       data-options="
                        url:'/select/findDepartments',
                        valueField:'id',
                        textField:'name',
                        panelHeight:'auto'
                    ">
            <a href="javascript:void(0);" data-method="search" class="easyui-linkbutton" iconCls="icon-search">搜索</a>
            <%--当button按钮在form表单内部的时候,默认提交是submit提交--%>
            <button class="easyui-linkbutton" iconCls="icon-search">导出</button>
        </form>
    </div>
</div>

按钮添加事件

//获取到页面上所有的a标签
$("a").on("click",function () {
  var method = $(this).data("method");
  if (method) {
    console.debug(method)
    itsource[method]();
  }
});

  itsource = {

      /*打开回收站*/
    recycle :function() {

      $("#re_Dlg").dialog("setTitle", "回收站").dialog("open").dialog("center");
    },

     /*重置按钮*/
    reset:function(){
      /*$('#dg').datagrid('gotoPage', {
          page:1,
          callback:function () {
              $("#searchForm").form("clear");
              var param = $("#searchForm").serializeObject();
              $("#dg").datagrid('reload',param);
          }
      });*/
      window.location.reload();
    },

      /*查找按钮*/
     //需要先引入 jquery.jdirk.js 才可以使用这个方法
    search:function(){
      var param = $("#searchForm").serializeObject();
      $("#dg").datagrid('reload',param);
    },

      /*打开添加数据的弹框*/
    add:function () {
	  //清空表单
      $("#ff").form("clear");
	  //让tr pwd 的标签卡显示
      $("tr[pwd]").show();
	  //开启密码验证
      $("#password").textbox("enableValidation");
      $("#reqpassword").textbox("enableValidation");
	  //链式编程 依次是 打开弹框 设置标题 弹框居中 
      $("#dlg").dialog("open").dialog("setTitle","添加").dialog("center");
    },

      /*保存数据*/
    save:function(){
	  //获取id
      var idname = $("#ff input[name='id']").val();

      /*默认是保存*/
      url = "/employee/save";
      //如果有id 则是更新
      if (idname){
        url = "/employee/update";
      }

      $("#ff").form("submit",{
        url:url,
        onSubmit:function () {
          var info = $("#ff").form("validate");
          return info;
        },
        success:function (data) {
          var JSON_info = $.parseJSON(data);
          if (JSON_info.success) {
            $("#dlg").dialog("close");
            $("#dg").datagrid("reload");
          }else {
            $.messager.alert("错误", JSON_info.msg, "error");
          }
        }
      })
    },

      /*修改数据*/
    edit:function() {
      var row = $("#dg").datagrid("getSelections");
      if (!row) {
        $.messager.alert("警告","请选择一条信息喔","Error");
        return;
      }

      if (row.length > 1) {
        $.messager.alert("警告","只能选择一条信息喔","Error");
        return;
      }
      if(row.department){
        row.deptId = row.department.id;
      }

      $("#ff").form('load',row[0]);

      $("tr[pwd]").hide();

      $("#password").textbox("disableValidation");
      $("#reqpassword").textbox("disableValidation");

      $("#dlg").dialog("open").dialog("setTitle","修改").dialog("center");
    },

      /*将数据删除到回收站*/
    remove:function () {
      var row = $("#dg").datagrid("getSelections");
      if (!row.length){
        $.messager.alert("警告","请选择一条信息喔","Error");
        return;
      }

      var arrs = [];
      $.each(row,function (i, o) {
        arrs.push(o.id);
      })
      $.messager.confirm("提示","是否删除选中的数据",function (inf) {
        if (inf){
          $.get("/employee/delete",{ids:arrs.toString()},function (res) {
            if (res.success){
              $("#dg").datagrid("reload");
              $("#re_datagrid").datagrid("reload");
            }else {
              $.messager.alert("错误", res.msg, "error");
            }
          })
        }
      })
    },

      /*从数据库删除数据*/
    re_remove:function () {
        var row = $("#re_datagrid").datagrid("getSelections");
        if (!row.length){
            $.messager.alert("警告","请选择一条信息喔","Error");
            return;
        }

        var arrs = [];
        $.each(row,function (i, o) {
            arrs.push(o.id);
        })
        $.messager.confirm("提示","是否删除选中的数据",function (inf) {
            if (inf){
                $.get("/employee/re_delete",{ids:arrs.toString()},function (res) {
                    if (res.success){
                        $("#re_datagrid").datagrid("reload");
                    }else {
                        $.messager.alert("错误", res.msg, "error");
                    }
                })
            }
        })
    }
  }

后台数据

Controller层

public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;

    @RequestMapping("/index")
    public String index(Model model){

        model.addAttribute("users", employeeService.findAll());
        return "employee/employee";
    }
	//员工数据
    @RequestMapping("/datagrid")
    @ResponseBody
    public PageList<Employee> datagrid(EmployeeQuery query){
        //查询分页列表
        Page<Employee> page = employeeService.findPageByQueryAndSta(query);
        //把Page对象转为PageList对象
        return new PageList<Employee>(page);
    }
	//回收站数据
    @RequestMapping("/re_datagrid")
    @ResponseBody
    public PageList<Employee> re_datagrid(re_EmployeeQuery query){
        //查询分页列表
        Page<Employee> page = employeeService.findPageByQueryAndSta(query);
        //把Page对象转为PageList对象
        return new PageList<Employee>(page);
    }
    
	//存储方法
    @RequestMapping("/save")
    @ResponseBody
    public AjaxResult Save(Employee employee){
        return saveOrUpdate(employee);
    }

    /**
     * 只要在方法上面加了@ModelAttribute代表的意思就是
     * 在执行目标方法之前,总是先执行此方法
     */
    @ModelAttribute("updateEmployee")
    public Employee beforeEdit(Long id){
        if(id != null){
            Employee employee = employeeService.findById(id);
            //以后凡是有关联对象,把关联对象设置为空
            employee.setDepartment(null);
            return employee;
        }
        return null;
    }


	//更新方法
    @RequestMapping("/update")
    @ResponseBody
    public AjaxResult update(@ModelAttribute("updateEmployee") Employee employee){
        return saveOrUpdate(employee);
    }

    /**
     * 保存或者修改
     * @param employee
     * @return
     */
    public AjaxResult saveOrUpdate(Employee employee){
        try {
            System.out.println(employee);

            employeeService.save(employee);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, "操作失败:" + e.getMessage());
        }
    }

    /**
     * 从列表中删除到回收站(不在数据库中删除)
     * @param ids
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public AjaxResult delete(Long[] ids){
        Map<String, Object> map = new HashMap<>();
        try {
            for (Long id : ids) {
                this.update_status(id);
            }
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, "删除失败:" + e.getMessage());
        }
    }

    /**
     * 从回收站删除(从数据库删除)
     */
    @RequestMapping("/re_delete")
    @ResponseBody
    public AjaxResult re_delete(Long[] ids){
        Map<String, Object> map = new HashMap<>();
        try {
            System.out.println(ids);
            for (Long id : ids) {
                employeeService.delete(id);
            }
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, "删除失败:" + e.getMessage());
        }
    }

    /**
     * 从回收站还原到列表
     * @param id
     * @return
     */
    @RequestMapping("/update_status")
    @ResponseBody
    public AjaxResult update_status(Long id){

        Employee byId = employeeService.findById(id);

        if (byId.getRe_status() == 1){
            byId.setRe_status(0);
            Department department = new Department();
            department.setId(1L);
            byId.setDepartment(department);
        }else {
            byId.setRe_status(1);
        }
        System.out.println(byId);

        this.saveOrUpdate(byId);

        return new AjaxResult();
    }
}

Service层

@Override
public void save(Employee employee) {

    if (employee.getId() == null){
        employee.setPassword(Md5Util.createMd5(employee.getPassword()));
    }
    if(employee.getDepartment() != null && employee.getDepartment().getId()==null){
        employee.setDepartment(null);
    }
    super.save(employee);
}

@Override
public Employee findByUsername(String username) {
    return employeeRepository.findByUsername(username);
}

@Override
public Page<Employee> findPageByQueryAndSta(EmployeeQuery baseQuery) {
    Pageable pageable = new PageRequest(baseQuery.getBegin(), baseQuery.getRows() , baseQuery.createSort());
    Page<Employee> page = employeeRepository.findAll(baseQuery.createSpec(), pageable);
    return page;
}

@Override
public Page<Employee> findPageByQueryAndSta(re_EmployeeQuery baseQuery) {
    Pageable pageable = new PageRequest(baseQuery.getBegin(), baseQuery.getRows() , baseQuery.createSort());
    Page<Employee> page = employeeRepository.findAll(baseQuery.createSpec(), pageable);
    return page;
}

@Override
public Employee findOneByUsername(String login_name) {
    return employeeRepository.findOneByUsername(login_name);
}

EmployeeQuery

public class EmployeeQuery extends BaseQuery {

    private String username;
    private String email;
    private Long deptId;
    
    @Override
    public Specification createSpec() {
        Specification<Employee> specification = Specifications.<Employee>and()
                .like(StringUtils.isNotBlank(username), "username", "%" + username + "%")
                .like(StringUtils.isNotBlank(email), "email", "%" + email + "%")
                .eq(deptId != null, "department.id", deptId)
                .ne("re_status",1)
                .build();
        return specification;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public Long getDeptId() {
        return deptId;
    }
    public void setDeptId(Long deptId) {
        this.deptId = deptId;
    }
}

BaseQuery

public abstract class BaseQuery {

    //当前页
    private Integer page = 1;
    //每页条数
    private Integer rows = 10;
    //根据指定的字段进行排序
    private String orderByName;
    //默认的排序规则
    private String orderByType = "ASC";

    /**
     * 约束子类必须拥有该查询条件的方法
     * @return
     */
    public abstract Specification createSpec();

    /**
     * 抽取公共的排序
     * @return
     * 该方法是由query调用的
     */
    public Sort createSort(){
        Sort sort = null;
        if (StringUtils.isNotBlank(orderByName)){
            sort = new Sort("ASC".equals(this.orderByType.toUpperCase())?Sort.Direction.ASC :
                    Sort.Direction.DESC,this.orderByName);
        }
        return sort;
    }


    /**
     * 需要定义一个开始页
     * @return
     */
    public Integer getBegin(){
        return this.page - 1;
    }

Getter和Setter方法
相关标签: easyui