LayUI之CRUD

layui博客的基础上继续完善,这篇博客增加了数据表格来实现增删改查

Doa:

package com.zking.dao;

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

import com.zking.entity.User;
import com.zking.util.BaseDao;
import com.zking.util.PageBean;
import com.zking.util.StringUtils;

public class UserDao extends BaseDao {

	/**
	 * 查询结果携带角色名称
	 * @param user
	 * @param pageBean
	 * @return
	 * @throws Exception
	 */
	public List> userRole(User user, PageBean pageBean) throws Exception {
		String sql = "SELECT u.* ,\r\n" + 
				"(CASE \r\n" + 
				"	WHEN u.rid='1' THEN\r\n" + 
				"		'管理员'\r\n" + 
				"	WHEN u.rid='2' THEN\r\n" + 
				"		'发起者'\r\n" + 
				"	WHEN u.rid='3' THEN\r\n" + 
				"		'审批者'\r\n" + 
				"	WHEN u.rid='4' THEN\r\n" + 
				"		'参与者'\r\n" + 
				"	WHEN u.rid='5' THEN\r\n" + 
				"		'会议室管理员'	\r\n" + 
				"	ELSE\r\n" + 
				"		'其他'\r\n" + 
				"END\r\n" + 
				") rname\r\n" + 
				"FROM t_oa_user u where 1=1";
		String name = user.getName();
		if(StringUtils.isNotBlank(name)) {
			sql +=" and name like '%"+name+"%'";
		}
		return super.executeQuery(sql, pageBean);
	}

	public int add(User user) throws Exception {
		String sql = "insert into t_oa_user(name,loginName,pwd) values(?,?,?)";
		return super.executeUpdate(sql, user, new String[] {"name","loginName","pwd"});
	}
	
	public int del(User user) throws Exception {
		String sql = "delete from t_oa_user where id = ?";
		return super.executeUpdate(sql, user, new String[] {"id"});
	}
	
	public int edit(User user) throws Exception {
		String sql = "update t_oa_user set name=?,loginName=?,pwd=? where id = ?";
		return super.executeUpdate(sql, user, new String[] {"name","loginName","pwd","id"});
	}

}

servlet:

package com.zking.web;

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zking.dao.UserDao;
import com.zking.entity.User;
import com.zking.framework.ActionSupport;
import com.zking.framework.ModelDriver;
import com.zking.util.PageBean;
import com.zking.util.R;
import com.zking.util.ResponseUtil;

public class UserAction extends ActionSupport implements ModelDriver {
	
	private User user = new User();
	private UserDao ud = new UserDao();
		
	public void userRole(HttpServletRequest req, HttpServletResponse resp) {
		try {
			PageBean pageBean = new PageBean();
			pageBean.setRequest(req);
			List> userRole = ud.userRole(user, pageBean);
			ResponseUtil.writeJson(resp, R.ok(0, "查询成功", pageBean.getTotal(), userRole));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public void add(HttpServletRequest req, HttpServletResponse resp) {
		try {
			int add = ud.add(user);
			ResponseUtil.writeJson(resp, R.ok(0, "新增成功"));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public void del(HttpServletRequest req, HttpServletResponse resp) {
		try {
			int add = ud.del(user);
			ResponseUtil.writeJson(resp, R.ok(0, "删除成功"));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public void edit(HttpServletRequest req, HttpServletResponse resp) {
		try {
			int add = ud.edit(user);
			ResponseUtil.writeJson(resp, R.ok(0, "修改成功"));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	@Override
	public User getModel() {
		// TODO Auto-generated method stub
		return user;
	}

	

}

工具类: 

package com.zking.util;

import java.util.HashMap;

public class R extends HashMap{
	public R data(String key, Object value) {
		this.put(key, value);
		return this;
	}
	
	public static R ok(int code, String msg) {
		R r = new R();
		r.data("success", true).data("code", code).data("msg", msg);
		return r;
	}
	
	public static R error(int code, String msg) {
		R r = new R();
		r.data("success", false).data("code", code).data("msg", msg);
		return r;
	}
	
	public static R ok(int code, String msg,Object data) {
		R r = new R();
		r.data("success", true).data("code", code).data("msg", msg).data("data", data);
		return r;
	}
	
	public static R ok(int code, String msg, long count, Object data) {
		R r = new R();
		r.data("success", true).data("code", code).data("msg", msg).data("count", count).data("data", data);
		return r;
	}
}
package com.zking.util;

import java.util.HashMap;

public class R extends HashMap{
	public R data(String key, Object value) {
		this.put(key, value);
		return this;
	}
	
	public static R ok(int code, String msg) {
		R r = new R();
		r.data("success", true).data("code", code).data("msg", msg);
		return r;
	}
	
	public static R error(int code, String msg) {
		R r = new R();
		r.data("success", false).data("code", code).data("msg", msg);
		return r;
	}
	
	public static R ok(int code, String msg,Object data) {
		R r = new R();
		r.data("success", true).data("code", code).data("msg", msg).data("data", data);
		return r;
	}
	
	public static R ok(int code, String msg, long count, Object data) {
		R r = new R();
		r.data("success", true).data("code", code).data("msg", msg).data("count", count).data("data", data);
		return r;
	}
}

 jsp代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ include file="/common/header.jsp" %>




Insert title here
 







js代码: 

var element,layer,util,$;

layui.use(['element', 'layer', 'util'], function(){
   element = layui.element
  ,layer = layui.layer
  ,util = layui.util
  ,$ = layui.$;
  
  $.ajax({
	  url:'permission.action?methodName=menus',
			  dataType:'json',
			  success:function(data){
				  console.log(data)
				  var htmlStr = '';
				  $.each(data,function(i,n){
					  htmlStr +='
  • '; htmlStr +=''+n.text+''; if(n.hasChildren){ var children=n.children; htmlStr +='
    '; $.each(children,function(index,node){ htmlStr +='
    '+node.text+'
    '; }) htmlStr +='
    '; } htmlStr +='
  • '; }) $("#menu").html(htmlStr); element.render('menu'); } }); }); function openTab(title,content,id){ var $node = $('li[lay-id="'+id+'"]'); console.log($node) if($node.length == 0){ //新增一个Tab项 element.tabAdd('demo', { title: title //用于演示 ,content: "" ,id: id //实际使用一般是规定好的id,这里以时间戳模拟下 }) } element.tabChange('demo', id); //切换到:用户管理 }

     数据表jsp:

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
        <%@ include file="/common/header.jsp" %>
    
    
    
    
     
    Insert title here
    
    
    
    
    
    
    	

    js代码:

    var table,$,layer;
    var row;
    layui.use(['table','jquery'], function(){
      table = layui.table
      ,layer=layui.layer
      ,$=layui.jquery;
      
      initTable();
      
      
      $("#btn_search").click(function(){
    	  query();
      })
      
      $("#btn_add").click(function(){
    	  row = null;
    	  edit("新增界面");
      })
      
    });
    
    function edit(title){
    	 layer.open({
    	       type: 2,                    //layer提供了5种层类型。可传入的值有:0(信息框,默认)1(页面层)2(iframe层)3(加载层)4(tips层)
    	       title:title,
    	       area: ['660px', '340px'],   //宽高
    	       skin: 'layui-layer-rim',    //样式类名
    	       content: 'jsp/system/userEdit.jsp', //书本编辑页面
    	       btn:['保存','关闭'],
    	       yes: function(index, layero){
    	    	   //调用子页面中提供的getData方法,快速获取子页面的form表单数据
    	           let data= $(layero).find("iframe")[0].contentWindow.getData();
    	           console.log(data);
    	           //判断title标题
    	           let methodName="add";
    	           if(title=="编辑")
    	        	   methodName="edit";
    	           $.post('user.action?methodName='+methodName,
    	        		   data,function(rs){
    	        	   if(rs.success){
    	        		   //关闭对话框
    	        		   layer.closeAll();
    	        		   //调用查询方法刷新数据
    	        		   query();
    	        	   }else{
    	        		   layer.msg(rs.msg,function(){});
    	        	   }
    	           },'json');
    	       },
    	       btn2: function(index, layero){
    	    	   layer.closeAll();
    	       }
    	    });
    	 
    }
    
    function query(){
    	table.reload('test', {
    		  where: { //设定异步数据接口的额外参数,任意设
    		    name: $("#name").val()
    		  }
    	 ,request: {
    		    pageName: 'page' //页码的参数名称,默认:page
    		    ,limitName: 'rows' //每页数据量的参数名,默认:limit
    		  }
    		}); //只重载数据
    }
    
    function initTable(){
    	table.render({
    	    elem: '#test'
    	    ,url:'user.action?methodName=userRole'
    	    ,toolbar: '#toolbarDemo' //开启头部工具栏,并为其绑定左侧模板
    	    ,defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义,去除该参数即可
    	      title: '提示'
    	      ,layEvent: 'LAYTABLE_TIPS'
    	      ,icon: 'layui-icon-tips'
    	    }]
    	    ,title: '用户数据表'
    	    ,cols: [[
    	      {type: 'checkbox', fixed: 'left'}
    	      ,{field:'id', title:'ID', width:80, fixed: 'left', unresize: true, sort: true}
    	      ,{field:'loginName', title:'账户名', width:120, edit: 'text'}
    	      ,{field:'name', title:'用户名', width:150, edit: 'text', templet: function(res){
    	        return ''+ res.name +''
    	      }}
    	      ,{field:'pwd', title:'密码', width:80, edit: 'text', sort: true}
    	      ,{field:'rname', title:'角色名称', width:100}
    	      ,{fixed: 'right', title:'操作', toolbar: '#barDemo', width:150}
    	    ]]
    	    ,page: true
    	  });
    	  
    	  //头工具栏事件
    	  table.on('toolbar(test)', function(obj){
    	    var checkStatus = table.checkStatus(obj.config.id);
    	    switch(obj.event){
    	      case 'getCheckData':
    	        var data = checkStatus.data;
    	        layer.alert(JSON.stringify(data));
    	      break;
    	      case 'getCheckLength':
    	        var data = checkStatus.data;
    	        layer.msg('选中了:'+ data.length + ' 个');
    	      break;
    	      case 'isAll':
    	        layer.msg(checkStatus.isAll ? '全选': '未全选');
    	      break;
    	      
    	      //自定义头工具栏右侧图标 - 提示
    	      case 'LAYTABLE_TIPS':
    	        layer.alert('这是工具栏右侧自定义的一个图标按钮');
    	      break;
    	    };
    	  });
    	  
    	  //监听行工具事件
    	  table.on('tool(test)', function(obj){
    	    row = obj.data;
    	    //console.log(obj)
    	    if(obj.event === 'del'){
    	    	layer.confirm('确认删除吗?', {icon: 3, title:'提示'}, function(index){
    				  $.post('user.action',{
    					  'methodName':'del',
    					  'id':row.id
    				  },function(rs){
    					  if(rs.success){
    		        		   //调用查询方法刷新数据
    		        		   query();
    		        	   }else{
    		        		   layer.msg(rs.msg,function(){});
    		        	   }
    				  },'json');
    				  layer.close(index);
    				});
    	    } else if(obj.event === 'edit'){
    	    	edit('编辑');
    	     
    	    }
    	  });
    	
    }
    

    编辑界面:

    <%@ page language="java" contentType="text/html; charset=UTF-8"
    	pageEncoding="UTF-8"%>
    <%@include file="/common/header.jsp"%>
    
    
    
    
    
    用户新增
    
    
    
    

    Js代码:

    let layer,form,$;
    layui.use(['layer','form','jquery'],function(){
    	layer=layui.layer,form=layui.form,$=layui.jquery;
    	initData();
    });
    
    function initData(){
    	console.log(parent.row);
    	if(null!=parent.row){
    	     //因为layui.each内部的逻辑问题导致的所以要先深拷贝一份然后再去val
    	     //parent.row:表格行对象
    	     form.val('user',$.extend({}, parent.row||{}));
    	     $('#name').attr('readonly','readonly');
    	}
    }
    
    function getData(){
        return form.val('user');
    }
    

     

    你可能感兴趣的:(layui,前端,javascript)