EasyUI - comprehensive case (combined with crud in the background)

Keywords: Javascript JQuery Shiro Database

Article directory

Common part code

//Pop up box should be modal box by default
$.fn.dialog.defaults.modal = true;
//Pop up box should be closed by default
$.fn.dialog.defaults.closed = true;
//Default authentication information
$.fn.textbox.defaults.missingMessage="Please fill in this column";

Header.js

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<link rel="stylesheet" href="/static/click/font_click.css">
<!-- easyui The core of css -->
<link rel="stylesheet" id="easyuiTheme" href="/static/easyui/themes/default/easyui.css">
<!-- easyui Icon css -->
<link rel="stylesheet" href="/static/easyui/themes/icon.css">
<!-- easyui Color -->
<link rel="stylesheet" href="/static/easyui/themes/color.css">
<!-- easyui Extended validation related css -->
<link rel="stylesheet" href="/static/easyui/validatebox/jeasyui.extensions.validatebox.css"  />
<!-- jquery The core of js -->
<script type="text/javascript" src="/static/easyui/jquery.min.js"></script>
<script type="text/javascript" src="/static/easyui/jquery.cookie.js"></script>
<!-- easyui The core of js -->
<script type="text/javascript" src="/static/easyui/jquery.easyui.min.js"></script>
<!-- Introduce jquery Extension js -->
<script type="text/javascript" src="/static/easyui/jquery.jdirk.js"></script>
<%--<script type="text/javascript" src="/static/easyui/jquery.edatagrid.js"></script>--%>
<!-- Sinicization js -->
<script type="text/javascript" src="/static/easyui/locale/easyui-lang-zh_CN.js"></script>
<!-- Introduce easyui Verification related 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>

Master page layout

<body class="easy
ui-layout">
    <div data-options="region:'north',split:true" style="height:100px;">
        Header information (mainly including logo, user name, etc.)
    </div>
    <div data-options="region:'south',split:true" style="height:100px;">
        Copyright information, etc
    </div>
    < div data options = "region: 'West', Title: 'menu information', split: true" style = "width: 230px;" >
        Main storage menu information (tree menu)
    </div>
    < div data options = "region: 'center', Title: 'welcome!!! '" style="padding:5px;background:#eee;">
        Main body content (show welcome page) - > main body in layout must have
    </div>
</body>

Left tree menu layout

h5:

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

js:

$("#menu").tree({
    url:"/treeMenu",
    //animation
    animate:true,
    //Defines whether to display dashed lines on tree controls
    lines:true,
    onClick:function(node){
    	//Determine whether it is a secondary menu
        if(node.url){
        	//Determine if the label is open in the tab
            if($("#tab").tabs("exists",node.text)){
            	//Jump if already exists
                $("#tab").tabs("select",node.text);
            }else {
            	//Add if not
                $("#tab").tabs("add",{
                    title:node.text,
                    content:"<iframe width='100%' height='100%' frameborder='0' src='"+node.url+"'/>",
                    closable:true
                });
            }
        }
    }
});

Background data preparation

service level

    public List<Menu>  findMenusByLoginUser() {
        //Create a collection of install level 1 menus
        List<Menu> parents = new ArrayList<>();
        //Query the menu owned by the user (all obtained are secondary menus)
        List<Menu> menus = menuRepository.findMenusByLoginUser(UserContext.getUserBySession());
        for (Menu menu : menus) {
            //Get the parent menu of the menu
            Menu parent = menu.getParent();
            //Determine whether the menu is in the set with the first level menu
            if (!parents.contains(parent)){
                //Put into collection if not
                parents.add(parent);
            }
            //Put the secondary menu in the primary menu
             parent.getChildren().add(menu);
        }
        return parents;
    }

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

Staff management

Data list (loading data by HTML)

<table id="dg" class="easyui-datagrid" data-options="
    fit:true,
    url:'/employee/datagrid',
    title:'Employee list',
    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}}">User name</th>
        <th data-options="field:'password',width:'20%',align:'center'" editor="{type:'validatebox',options:{required:true}}">Password</th>
        <th data-options="field:'email',width:'20%',align:'center'" editor="{type:'validatebox',options:{required:true,validType:'email'}}">mailbox</th>
        <th data-options="field:'headImage',width:'15%',align:'center',formatter:formatterHeadImage">Head portrait</th>
        <th data-options="field:'age',width:'10%',align:'center',sortable:true" editor="numberbox">Age</th>
        <th data-options="field:'department',width:'20%',align:'center',formatter:formatterDept">department</th>
    </tr>
    </thead>
</table>

Format departments and pictures

/*Picture formatting*/
function formatterHeadImage(v,r,i){
  return "<img alt='No picture' width='50' src='"+v+"' />";
}

/*Display department*/
function formatterDept(v,r,i){
  if (v){
    return v.name;
  }
}

Recycle bin data (loading data through 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

 /*Recycle bin js*/
  //Get the corresponding table
  var re_datagrid = $("#re_datagrid");
  //jquery object corresponding to pop-up box
  var re_Dlg = $("#re_Dlg");
  //Object corresponding to the pop-up form
  var re_ff = $("#re_ff");


    /*Create recycle bin table double click to restore data*/
  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("Tips","Restore selected data or not",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("error", res.msg, "error");
                    }
                })
            }
        })
    },

    columns :[[
      {field :'id',title:'Name',width :'6%',align :'center',checkbox:true},
      {field:'username',title:'User name',width:'14%',align:'center'},
      {field:'password',title:'Password',width:'20%',align:'center'},
      {field:'email',title:'mail',width:'15%',align:'center'},
      {field:'headImage',title:'Head portrait',width:'15%',align:'center',formatter:formatterHeadImage},
      {field:'age',title:'Age',width:'10%',align:'center'},
      {field:'department',title:'department',width:'20%',align:'center',formatter:formatterDept}
    ]]
  });

Add button and event

Ready button

<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">Add to</a>
        </shiro:hasPermission>
        <shiro:hasPermission name="employee:update">
            <a href="javascript:void(0);" data-method="edit" class="easyui-linkbutton" iconCls="icon-edit" plain="true">modify</a>
        </shiro:hasPermission>
        <shiro:hasPermission name="employee:delete">
            <a href="javascript:void(0);" data-method="remove" class="easyui-linkbutton" iconCls="icon-remove" plain="true">delete</a>
        </shiro:hasPermission>
        <a href="javascript:void(0);" data-method="reset" class="easyui-linkbutton" iconCls="icon-reload" plain="true">Reset</a>

        <a href="javascript:void(0);" data-method="recycle" class="easyui-linkbutton" iconCls="icon-back" plain="true">recycle bin</a>
    </div>
    //Advanced query
    <div style=" position: fixed ! important; right: 10px; top: 40px;">
        <form id="searchForm" method="post" action="/employee/download">
            User name:<input class="easyui-textbox" type="text" name="username"/>
            mailbox:<input class="easyui-textbox" type="text" name="email"/>
                department: <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">search</a>
            <%--When button Button in form When inside the form,Default commit is submit Submission--%>
            <button class="easyui-linkbutton" iconCls="icon-search">export</button>
        </form>
    </div>
</div>

Button add event

//Get all a tags on the page
$("a").on("click",function () {
  var method = $(this).data("method");
  if (method) {
    console.debug(method)
    itsource[method]();
  }
});

  itsource = {

      /*Open recycle bin*/
    recycle :function() {

      $("#re_Dlg").dialog("setTitle", "recycle bin").dialog("open").dialog("center");
    },

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

      /*Lookup button*/
     //You need to introduce jquery.jdirk.js to use this method
    search:function(){
      var param = $("#searchForm").serializeObject();
      $("#dg").datagrid('reload',param);
    },

      /*Open the pop-up box for adding data*/
    add:function () {
	  //Empty the form
      $("#ff").form("clear");
	  //Let tr pwd's label card display
      $("tr[pwd]").show();
	  //Turn on password verification
      $("#password").textbox("enableValidation");
      $("#reqpassword").textbox("enableValidation");
	  //The chain programming is successively to open the pop-up box, set the title pop-up box and center it 
      $("#dlg").dialog("open").dialog("setTitle","Add to").dialog("center");
    },

      /*Save data*/
    save:function(){
	  //Get id
      var idname = $("#ff input[name='id']").val();

      /*Save by default*/
      url = "/employee/save";
      //Update if there is an 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("error", JSON_info.msg, "error");
          }
        }
      })
    },

      /*Modifying data*/
    edit:function() {
      var row = $("#dg").datagrid("getSelections");
      if (!row) {
        $.messager.alert("warning","Please select a message","Error");
        return;
      }

      if (row.length > 1) {
        $.messager.alert("warning","Only one message can be selected","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","modify").dialog("center");
    },

      /*Delete data to recycle bin*/
    remove:function () {
      var row = $("#dg").datagrid("getSelections");
      if (!row.length){
        $.messager.alert("warning","Please select a message","Error");
        return;
      }

      var arrs = [];
      $.each(row,function (i, o) {
        arrs.push(o.id);
      })
      $.messager.confirm("Tips","Delete selected data",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("error", res.msg, "error");
            }
          })
        }
      })
    },

      /*Delete data from database*/
    re_remove:function () {
        var row = $("#re_datagrid").datagrid("getSelections");
        if (!row.length){
            $.messager.alert("warning","Please select a message","Error");
            return;
        }

        var arrs = [];
        $.each(row,function (i, o) {
            arrs.push(o.id);
        })
        $.messager.confirm("Tips","Delete selected data",function (inf) {
            if (inf){
                $.get("/employee/re_delete",{ids:arrs.toString()},function (res) {
                    if (res.success){
                        $("#re_datagrid").datagrid("reload");
                    }else {
                        $.messager.alert("error", res.msg, "error");
                    }
                })
            }
        })
    }
  }

Background data

Controller layer

public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;

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

        model.addAttribute("users", employeeService.findAll());
        return "employee/employee";
    }
	//Employee data
    @RequestMapping("/datagrid")
    @ResponseBody
    public PageList<Employee> datagrid(EmployeeQuery query){
        //Query page list
        Page<Employee> page = employeeService.findPageByQueryAndSta(query);
        //Convert Page object to PageList object
        return new PageList<Employee>(page);
    }
	//Recycle bin data
    @RequestMapping("/re_datagrid")
    @ResponseBody
    public PageList<Employee> re_datagrid(re_EmployeeQuery query){
        //Query page list
        Page<Employee> page = employeeService.findPageByQueryAndSta(query);
        //Convert Page object to PageList object
        return new PageList<Employee>(page);
    }
    
	//Storage method
    @RequestMapping("/save")
    @ResponseBody
    public AjaxResult Save(Employee employee){
        return saveOrUpdate(employee);
    }

    /**
     * Just add @ ModelAttribute to the method, which means
     * Always execute the target method before executing it
     */
    @ModelAttribute("updateEmployee")
    public Employee beforeEdit(Long id){
        if(id != null){
            Employee employee = employeeService.findById(id);
            //In the future, for all associated objects, set the associated object to null
            employee.setDepartment(null);
            return employee;
        }
        return null;
    }


	//Update method
    @RequestMapping("/update")
    @ResponseBody
    public AjaxResult update(@ModelAttribute("updateEmployee") Employee employee){
        return saveOrUpdate(employee);
    }

    /**
     * Save or modify
     * @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, "operation failed:" + e.getMessage());
        }
    }

    /**
     * Remove from list to recycle bin (not in database)
     * @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, "Delete failed:" + e.getMessage());
        }
    }

    /**
     * Remove from recycle bin (remove from database)
     */
    @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, "Delete failed:" + e.getMessage());
        }
    }

    /**
     * Restore from recycle bin to list
     * @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 level

@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 {

    //Current page
    private Integer page = 1;
    //Number of pages per page
    private Integer rows = 10;
    //Sort by specified field
    private String orderByName;
    //Default collation
    private String orderByType = "ASC";

    /**
     * Constraint subclass must have the method of the query condition
     * @return
     */
    public abstract Specification createSpec();

    /**
     * Extract common sort
     * @return
     * This method is called by 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;
    }


    /**
     * Need to define a start page
     * @return
     */
    public Integer getBegin(){
        return this.page - 1;
    }

Getter and Setter Method
Published 53 original articles, won praise 9, visited 699
Private letter follow

Posted by mwkemo on Sat, 25 Jan 2020 07:54:30 -0800