layui的增刪改查

爕藝響發表於2019-07-10

實體類

User

public class User{	
	private String user_id;
	private String user_name;
	private String part_names;
	private String part_ids;

	
	
	public User(Map<String, Object> map) {
		super();
		this.user_id = map.get("user_id").toString();
		this.user_name = map.get("user_name").toString();
		this.part_names = map.get("part_names").toString();
		this.part_ids = map.get("part_ids").toString();
	}



	public String getUser_id() {
		return user_id;
	}



	public void setUser_id(String user_id) {
		this.user_id = user_id;
	}



	public String getUser_name() {
		return user_name;
	}



	public void setUser_name(String user_name) {
		this.user_name = user_name;
	}



	public String getPart_names() {
		return part_names;
	}



	public void setPart_names(String part_names) {
		this.part_names = part_names;
	}



	public String getPart_ids() {
		return part_ids;
	}



	public void setPart_ids(String part_ids) {
		this.part_ids = part_ids;
	}
	

TreeNode

public class TreeNode {
	private String id;
	private String name;
	private Map<String, Object> attributes = new HashMap<>();
	private List<TreeNode> children = new ArrayList<>();

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Map<String, Object> getAttributes() {
		return attributes;
	}

	public void setAttributes(Map<String, Object> attributes) {
		this.attributes = attributes;
	}

	public List<TreeNode> getChildren() {
		return children;
	}

	public void setChildren(List<TreeNode> children) {
		this.children = children;
	}

	public TreeNode(String id, String text, Map<String, Object> attributes, List<TreeNode> children) {
		super();
		this.id = id;
		this.name = name;
		this.attributes = attributes;
		this.children = children;
	}

	public TreeNode() {
		super();
	}

	@Override
	public String toString() {
		return "TreeNode [id=" + id + ", name=" + name + ", attributes=" + attributes + ", children=" + children + "]";
	}

}

dao方法

UserDao

/**
 * 使用者
 * 
 * @author 20190313
 *
 */
public class UserDao extends JsonBaseDao {

	/**
	 *登入
	 * 
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	public User login(Map<String, String[]> paramMap) throws Exception {
		String user_id = JsonUtils.getParamVal(paramMap, "user_id");
		String sql = "select * from `user` where user_name = ? and  pwd = ? and statu = 1";
		List<Map<String, Object>> list = super.executeQuery(sql, new String[] {"user_name", "pwd"}, paramMap,
				null);
		if (list != null && list.size() > 0) {
			Map<String, Object> map = list.get(0);
			bindingStr(map.get("user_id").toString(), map);
			return new User(map);
		}
		return null;
	}

	/**
	 * 角色資料繫結
	 * 
	 * @return
	 */
	private void bindingStr(String user_id, Map<String, Object> map) throws Exception {
		String sql = "select a.part_id, a.part_name from part a, user_and_part b where a.part_id = b.part_id and b.user_id = "
				+ user_id;
		List<Map<String, Object>> list = super.executeQuery(sql, null);
		String part_names = "";
		String part_ids = "";
		for (Map<String, Object> m : list) {
			part_names += "," + m.get("part_name");
			part_ids += "," + m.get("part_id");
		}
		if (part_names.length() > 0) {
			part_ids = part_ids.substring(1);
			part_names = part_names.substring(1);
		}

		map.put("part_names", part_names);
		map.put("part_ids", part_ids);
	}

	/**
	 * 新增
	 * 
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	public int add(Map<String, String[]> paramMap) throws Exception {
		String sql = "insert into `user` (user_name, pwd, statu)values (?, ?, 1)";
		int n = super.executeUpdate(sql, new String[] { "user_name", "pwd" }, paramMap);
		//獲取當前插入id
		int maxId = executeByInteger("select max(user_id) from user ");
		// 角色資料插入
		String[] part_ids = JsonUtils.getParamVal(paramMap, "part_ids").split(",");
		bindingPart(maxId + "", part_ids);
		return n;
	}

	/**
	 *想使用者角色表新增繫結資料(會將改使用者以前的所有所有繫結資訊刪除)
	 * 
	 * @param user_id
	 * @param part_ids
	 */
	public void bindingPart(String user_id, String[] part_ids) {
		String sql = "delete from user_and_part where user_id = " + user_id;
		super.executeUpdate(sql);
		for (String part_id : part_ids) {
			super.executeUpdate("insert into user_and_part values(" + user_id + "," + part_id + ")");
		}
	}

	/**
	 * 刪除
	 * 
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	public int remove(Map<String, String[]> paramMap) throws Exception {
		String sql = "delete from `user` WHERE user_id = ?";
		// 刪除使用者繫結角色
		super.executeUpdate("delete from user_and_part where user_id =" + JsonUtils.getParamVal(paramMap, "user_id"));
		return super.executeUpdate(sql, new String[] { "user_id" }, paramMap);
	}

	/**
	 * 修改
	 * 
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	public int edit(Map<String, String[]> paramMap) throws Exception {
		String sql = "update `user` set user_name = ?, pwd = ? where user_id = ?";
		int n = super.executeUpdate(sql, new String[] { "user_name", "pwd", "user_id" }, paramMap);
		String[] part_ids = JsonUtils.getParamVal(paramMap, "part_ids").split(",");
		bindingPart(JsonUtils.getParamVal(paramMap, "user_id"), part_ids);
		return n;
	}

	/**
	 * 修改狀態
	 * 
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	public int eidtStatu(Map<String, String[]> paramMap) throws Exception {
		String sql = "update `user` set statu = ? where user_id = ?";
		return super.executeUpdate(sql, new String[] { "statu", "user_id" }, paramMap);
	}


	/**
	 *  使用者名稱是否重複
	 * 
	 * @return
	 */
	public boolean isName(Map<String, String[]> paramMap) throws Exception {
		List<Map<String, Object>> list = null;
		if(StringUtils.isNotBlank(JsonUtils.getParamVal(paramMap, "user_id"))) {
			String sql = "select user_id from user where user_id != ? and user_name = ?";
			 list = super.executeQuery(sql, new String[] { "user_id", "user_name" }, paramMap, null);		
		}else {
			String sql = "select user_id from user where user_name = ?";
			 list = super.executeQuery(sql, new String[] {"user_name" }, paramMap, null);		
		}	
		return list != null && list.size() > 0;
	}


	/**
	 *查詢 
	 * 
	 * @param paramMap
	 * @param pageBean
	 * @return
	 * @throws Exception
	 */
	public List<Map<String, Object>> query(Map<String, String[]> paramMap, PageBean pageBean) throws Exception {
		String sql = "select user_id, user_name, pwd, statu from `user` where true ";
		
		String user_name = JsonUtils.getParamVal(paramMap, "user_name");
		if (StringUtils.isNotBlank(user_name)) {
			sql += " and user_name like '%" + user_name + "%' ";
		}
		String user_id = JsonUtils.getParamVal(paramMap, "user_id");
		if (StringUtils.isNotBlank(user_id)) {
			sql += " and user_id = " + user_id;
		}
		//帶角色查詢
		String part_ids = JsonUtils.getParamVal(paramMap, "part_ids");
		if (StringUtils.isNotBlank(part_ids)) {
			sql += " and user_id in (" + 
					"	select user_id from user_and_part where part_id in ("+part_ids+") " + 
					")";
		}
		
		List<Map<String, Object>> list = super.executeQuery(sql, pageBean);

		//使用者的角色對應資料繫結(角色名和id)
		for (Map<String, Object> map : list) {
			bindingStr(map.get("user_id").toString(), map);
		}
		return list;
	}

}

工具類

web

BaseAction

public class BaseAction implements ServletRequestAware, ServletResponseAware{
	
	protected HttpServletResponse response;
	protected HttpServletRequest request;
	protected HttpSession session;
	protected ServletContext application;
	
	
	protected final static String SUCCESS = "success";
	protected final static String FAIL = "fail";
	protected final static String LIST = "list";
	protected final static String ADD = "add";
	protected final static String EDIT = "edit";
	protected final static String DETAIL = "detail";
	
	
	protected Object result;
	protected Object msg;
	protected int code;

	public Object getResult() {
		return result;
	}

	public Object getMsg() {
		return msg;
	}

	public int getCode() {
		return code;
	}

	@Override
	public void setServletResponse(HttpServletResponse arg0) {
		this.response = arg0;
		
	}

	@Override
	public void setServletRequest(HttpServletRequest arg0) {
		this.request = arg0;
		this.session = arg0.getSession();
		this.application = arg0.getServletContext();
	}
	

}

UserAction


public class UserAction extends BaseAction {

	private UserDao userDao = new UserDao();

	/**
	 * 查詢
	 * 
	 * @return
	 * @throws SQLException
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 */
	public String query() throws Exception {
		PageBean pageBean = new PageBean();
		pageBean.setPageBean(request);
		List<Map<String, Object>> list = userDao.query(request.getParameterMap(), pageBean);
		Map<String, Object> map = new HashMap<>();
		map.put("code", 0);
		map.put("count", pageBean.getTotal());
		map.put("data", list);
		// 以json格式返回
		ResponseUtil.writeJSON(response, map);
		return null;
	}

	/**
	 * 刪除
	 * 
	 * @return
	 * @throws SQLException
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 */
	public String remove() throws Exception {
		// 以json格式輸出
		ResponseUtil.writeJSON(response, userDao.remove(request.getParameterMap()));
		return null;
	}

	/**
	 * 登入 1登入成功,-1登入失敗
	 * 
	 * @return
	 * @throws SQLException
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 */
	public String login() throws Exception {
		User user = userDao.login(request.getParameterMap());
		// 判斷
		if (user != null) {
			//將user物件放入sesion中
			request.getSession().setAttribute("user", user);
			ResponseUtil.writeJSON(response, 1);
			return null;
		}
		ResponseUtil.writeJSON(response, -1);
		return null;
	}

	/**
	 * 增加
	 * 
	 * @return
	 * @throws SQLException
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 */
	public String add() throws Exception {
		// 判斷使用者名稱是重複
		if (userDao.isName(request.getParameterMap())) {
			// 使用者名稱重複返回-2
			ResponseUtil.writeJSON(response, -2);
			return null;
		}
		// 以json格式返回
		ResponseUtil.writeJSON(response, userDao.add(request.getParameterMap()));
		return null;
	}

	/**
	 * 修改
	 * 
	 * @return
	 * @throws SQLException
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 */
	public String edit() throws Exception {
		// 判斷使用者名稱是重複
		if (userDao.isName(request.getParameterMap())) {
			// 使用者名稱重複返回-2
			ResponseUtil.writeJSON(response, -2);
			return null;
		}
		
		ResponseUtil.writeJSON(response, userDao.edit(request.getParameterMap()));
		return null;
	}

	/**
	 * ̬修改使用者狀態
	 * 
	 * @return
	 * @throws SQLException
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 */
	public String eidtStatu() throws Exception {
		ResponseUtil.writeJSON(response, userDao.eidtStatu(request.getParameterMap()));
		return null;
	}
	
	/**
	 *使用者退出登入
	 * @return
	 * @throws Exception
	 */
	public String exit() throws Exception {
		//退出登入
		request.getSession().removeAttribute("user");
		ResponseUtil.writeJSON(response, 1);
		return null;
	}

前臺介面

login.js

layui.config({
    base: "static/js/"
}).use(['form', 'layer'], function () {
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : parent.layer,
        $ = layui.jquery;
    //獲取絕對路徑
    var path = $("#path").val();
    //登入按鈕事件
    form.on("submit(login)", function (data) {
        // $.ajaxSettings.async = false;
        $.post(path + "/sy/userAction_login.action", {
            user_name: $('#user_name').val(),
            pwd: $('#pwd').val()
        }, function (data) {
        	console.log(data);
            if (data > 0) {//登入成功
                layer.msg("登入成功", {icon:1,time: 1000}, function () {
                    parent.location.href = path + '/index.jsp';
                })
            } else {
                layer.msg("登入失敗,帳號或密碼錯誤或帳號不可用", {icon:2,time: 1000}, function () {
                })
            }

        })
        return false;
    })
});

userManagement.js

var path = document.getElementById("path").value;

layui.config({
	base : path + '/static/js/' // 此處寫的相對路徑, 實際以專案中的路徑為準
}).extend({
	formSelects : 'formSelects-v3'
});

// 使用者管理
layui
		.use(
				[ 'table', 'form', 'jquery', 'formSelects' ],
				// , 'from'
				function() {
					var table = layui.table, form = layui.form, formSelects = layui.formSelects;
					// 第一個例項
					table.render({
						elem : '#LAY_table_user',
						// height: 300,
						url : path + '/sy/userAction_query.action'// 資料介面
						,
						// defaultToolbar : [ 'filter', 'print', 'exports' ],
						page : true // 開啟分頁
						,
						limit : 10,
						limits : [ 5, 10, 15 ],
						cellMinWidth : 80,
						cols : [ [ {
							field : 'user_id',
							title : '編號',
							sort : true,
						// width: 80,
						}, {
							field : 'user_name',
							title : '使用者名稱',
						// width: 80,
						},{
							fixed : 'right',
							title : '操作',
							align : 'center',
							toolbar : '#barDemo'
						} ] ],
						id : 'testReload',

					});
					table.on('checkbox(user)', function(obj) {
						console.log(obj)
					});

					// 上方選單
					var $ = layui.$, active = {
						// 查詢
						reload : function() {
							// 執行過載
							table.reload('testReload', {
								page : {
									curr : 1
								// 重新從第 1 頁開始
								},
								where : {
									user_name : $('#user_name').val(),
									part_ids : formSelects.value(
											'user_part_id', 'valStr')
								}
							});
						},
						add : function() { // 新增
							$('#user_names').prop('disabled', false)// 設定可用
							$('#user_names').removeClass('layui-disabled')
							layer.open({
								type : 1,
								title : '新增使用者',
								maxmin : true,
								shadeClose : true, // 點選遮罩關閉層
								area : [ '80%', '80%' ],
								content : $('#box1'),
								btn : [ '確定', '取消' ],
								success : function(layero, index) {// 彈出後執行的函式
									formSelects.value('user_part_ids', []);
								},
								yes : function(index, layero) {// 確定執行函式

									// 執行新增方法
									$.post(path
											+ '/sy/userAction_add.action', {
										user_name : $('#user_names').val(),// 使用者名稱
										pwd : $('#pwd').val(),// 密碼
										part_ids : formSelects.value(
												"user_part_ids", 'valStr')
									}, function(data) {
										if (data > 0) {
											layer.alert('新增成功', {
												icon : 1,
												title : '提示'
											}, function(i) {
												layer.close(i);
												layer.close(index);// 關閉彈出層
												$("#users")[0].reset()// 重置form
											})
											table.reload('testReload', {// 過載表格
												page : {
													curr : 1
												// 重新從第 1 頁開始
												}
											})
										} else if (data == -2) {
											layer.msg('新增失敗,使用者名稱不能重複')
										} else {
											layer.msg('新增失敗')
										}
									})

								},
								cancel : function(index, layero) {
									$("#users")[0].reset()// 重置form
									layer.close(index)
								}
							});
						}
					}
					$('.layui-form .layui-btn').on('click', function() {
						var type = $(this).data('type');
						active[type] ? active[type].call(this) : '';
					});

					// table選單
					table.on('tool(user)', function(obj) {
						var data = obj.data;// 獲得當前行資料
						var layEvent = obj.event; // 獲得 lay-event
													// 對應的值(也可以是表頭的event引數對應的值)
						var tr = obj.tr; // 獲得當前行 tr 的DOM物件
						if (layEvent == 'edit') {// 編輯
							layer.open({
								type : 1,
								title : '編輯使用者',
								maxmin : true,
								shadeClose : true, // 點選遮罩關閉層
								area : [ '80%', '80%' ],
								content : $('#box1'),
								btn : [ '確定', '取消' ],
								success : function(layero, index) {// 彈出後執行的函式
									$('#pwd').val(data.pwd);
									$('#user_names').val(data.user_name);
									formSelects.value('user_part_ids', []);
									formSelects.value('user_part_ids',
											data.part_ids.split(","));
								},
								yes : function(index, layero) {// 確定回撥函式
									$.ajaxSettings.async = false;
									$.getJSON(path
											+ '/sy/userAction_edit.action', {
										pwd : $('#pwd').val(),
										user_id : data.user_id,
										user_name : $("#user_names").val(),
										part_ids : formSelects.value(
												"user_part_ids", 'valStr')
									}, function(data) {
										if (data > 0) {
											layer.alert('編輯成功', {
												icon : 1,
												title : '提示'
											}, function(i) {
												layer.close(i);
												layer.close(index);// 關閉彈出層
												$("#users")[0].reset()// 重置form
											})
											table.reload('testReload', {// 過載表格
												page : {
													curr : 1
												// 重新從第 1 頁開始
												}
											})
										} else if (data = -2) {
											layer.msg('使用者名稱重複')
										} else {
											layer.msg('編輯失敗')
										}
									})
								},
								cancel : function(index, layero) {
									$("#users")[0].reset()// 重置form
									layer.close(index)
								}
							})
						} else if (layEvent == 'begin') {// 啟用
							layer.confirm('確定啟用嗎???', {
								icon : 3,
								title : '提示'
							}, function(index) {
								$.getJSON(path
										+ '/sy/userAction_eidtStatu.action', {
									user_id : data.user_id,
									statu : 1
								}, function(data) {
									layer.close(index);
									table.reload('testReload', {
										page : {
											curr : 1
										// 重新從第 1 頁開始
										}
									})
								});
							})
						} else if (layEvent == 'end') {// end//禁用
							layer.confirm('確定禁用嗎???', {
								icon : 3,
								title : '提示'
							}, function(index) {
								$.getJSON(path
										+ '/sy/userAction_eidtStatu.action', {
									user_id : data.user_id,
									statu : 0
								}, function(data) {
									layer.close(index);
									table.reload('testReload', {
										page : {
											curr : 1
										// 重新從第 1 頁開始
										}
									})
								});
							})
						} else if (layEvent == 'del') {// 刪除
							layer.confirm('親親,你確定刪除嗎?', {
								icon : 3,
								title : '提示'
							}, function(index) {
								$.getJSON(
										path + '/sy/userAction_remove.action',
										{
											user_id : data.user_id
										}, function(data) {
											layer.close(index);
											table.reload('testReload', {
												page : {
													curr : 1
												// 重新從第 1 頁開始
												}
											})
										});
							})
						}
					});
				});

/**
 * 搜尋下拉框角色載入
 */
function part() {
	$.ajaxSettings.async = false
	$.getJSON(path + '/sy/partAction_select.action', {}, function(data) {
		var html = "<option value=''>直接選擇或搜尋選擇</option>";
		// 返回處理的方法
		$.each(data, function(index, item) {
			html += "<option value=" + item.part_id + ">" + item.part_name
					+ "</option>";
		});
		$('#user_part_id').html(html);
		$('#user_part_ids').html(html);
	})
}

part();

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登入</title>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/static/js/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="${pageContext.request.contextPath }/static/js/css/login.css">
    <script src="${pageContext.request.contextPath }/static/js/layui/layui.all.js"></script>
   
    <style>
        video {
            object-fit: fill;
            width: 1420px;
            height: 700px;
        }
    </style>
</head>
<body>

	<input type="hidden" id="path" value="${pageContext.request.contextPath}">
	
	<video class="video-player" preload="auto" autoplay="autoplay" loop="loop" data-height="1080"
	       width="1920">
	    <!---->
	    <source src="${pageContext.request.contextPath }/static/admin/mv.mp4" type="video/mp4">
	</video>
	
	<div class="video_mask"></div>
	<div class="login">
	    <h1>管理員登入</h1>
	    <form class="layui-form">
	        <div class="layui-form-item">
	            <input class="layui-input" id="user_name" name="user_name" placeholder="使用者名稱" value=""
	                   lay-verify="required" lay-verType="tips" type="text" autocomplete="off">
	        </div>
	        <div class="layui-form-item">
	            <input class="layui-input" id="pwd" name="pwd" placeholder="密碼" value=""
	                   lay-verify="required" lay-verType="tips" type="password" autocomplete="off">
	        </div>
	        <button class="layui-btn login_btn" lay-submit="" lay-filter="login">登入</button>
	    </form>
	</div>
	
	 <script src="${pageContext.request.contextPath }/static/js/login.js"></script>
	 
</body>
</html>

userManagement.jsp

var path = document.getElementById("path").value;

layui.config({
	base : path + '/static/js/' // 此處寫的相對路徑, 實際以專案中的路徑為準
}).extend({
	formSelects : 'formSelects-v3'
});

// 使用者管理
layui
		.use(
				[ 'table', 'form', 'jquery', 'formSelects' ],
				// , 'from'
				function() {
					var table = layui.table, form = layui.form, formSelects = layui.formSelects;
					// 第一個例項
					table.render({
						elem : '#LAY_table_user',
						// height: 300,
						url : path + '/sy/userAction_query.action'// 資料介面
						,
						// defaultToolbar : [ 'filter', 'print', 'exports' ],
						page : true // 開啟分頁
						,
						limit : 10,
						limits : [ 5, 10, 15 ],
						cellMinWidth : 80,
						cols : [ [ {
							field : 'user_id',
							title : '編號',
							sort : true,
						// width: 80,
						}, {
							field : 'user_name',
							title : '使用者名稱',
						// width: 80,
						},{
							fixed : 'right',
							title : '操作',
							align : 'center',
							toolbar : '#barDemo'
						} ] ],
						id : 'testReload',

					});
					table.on('checkbox(user)', function(obj) {
						console.log(obj)
					});

					// 上方選單
					var $ = layui.$, active = {
						// 查詢
						reload : function() {
							// 執行過載
							table.reload('testReload', {
								page : {
									curr : 1
								// 重新從第 1 頁開始
								},
								where : {
									user_name : $('#user_name').val(),
									part_ids : formSelects.value(
											'user_part_id', 'valStr')
								}
							});
						},
						add : function() { // 新增
							$('#user_names').prop('disabled', false)// 設定可用
							$('#user_names').removeClass('layui-disabled')
							layer.open({
								type : 1,
								title : '新增使用者',
								maxmin : true,
								shadeClose : true, // 點選遮罩關閉層
								area : [ '80%', '80%' ],
								content : $('#box1'),
								btn : [ '確定', '取消' ],
								success : function(layero, index) {// 彈出後執行的函式
									formSelects.value('user_part_ids', []);
								},
								yes : function(index, layero) {// 確定執行函式

									// 執行新增方法
									$.post(path
											+ '/sy/userAction_add.action', {
										user_name : $('#user_names').val(),// 使用者名稱
										pwd : $('#pwd').val(),// 密碼
										part_ids : formSelects.value(
												"user_part_ids", 'valStr')
									}, function(data) {
										if (data > 0) {
											layer.alert('新增成功', {
												icon : 1,
												title : '提示'
											}, function(i) {
												layer.close(i);
												layer.close(index);// 關閉彈出層
												$("#users")[0].reset()// 重置form
											})
											table.reload('testReload', {// 過載表格
												page : {
													curr : 1
												// 重新從第 1 頁開始
												}
											})
										} else if (data == -2) {
											layer.msg('新增失敗,使用者名稱不能重複')
										} else {
											layer.msg('新增失敗')
										}
									})

								},
								cancel : function(index, layero) {
									$("#users")[0].reset()// 重置form
									layer.close(index)
								}
							});
						}
					}
					$('.layui-form .layui-btn').on('click', function() {
						var type = $(this).data('type');
						active[type] ? active[type].call(this) : '';
					});

					// table選單
					table.on('tool(user)', function(obj) {
						var data = obj.data;// 獲得當前行資料
						var layEvent = obj.event; // 獲得 lay-event
													// 對應的值(也可以是表頭的event引數對應的值)
						var tr = obj.tr; // 獲得當前行 tr 的DOM物件
						if (layEvent == 'edit') {// 編輯
							layer.open({
								type : 1,
								title : '編輯使用者',
								maxmin : true,
								shadeClose : true, // 點選遮罩關閉層
								area : [ '80%', '80%' ],
								content : $('#box1'),
								btn : [ '確定', '取消' ],
								success : function(layero, index) {// 彈出後執行的函式
									$('#pwd').val(data.pwd);
									$('#user_names').val(data.user_name);
									formSelects.value('user_part_ids', []);
									formSelects.value('user_part_ids',
											data.part_ids.split(","));
								},
								yes : function(index, layero) {// 確定回撥函式
									$.ajaxSettings.async = false;
									$.getJSON(path
											+ '/sy/userAction_edit.action', {
										pwd : $('#pwd').val(),
										user_id : data.user_id,
										user_name : $("#user_names").val(),
										part_ids : formSelects.value(
												"user_part_ids", 'valStr')
									}, function(data) {
										if (data > 0) {
											layer.alert('編輯成功', {
												icon : 1,
												title : '提示'
											}, function(i) {
												layer.close(i);
												layer.close(index);// 關閉彈出層
												$("#users")[0].reset()// 重置form
											})
											table.reload('testReload', {// 過載表格
												page : {
													curr : 1
												// 重新從第 1 頁開始
												}
											})
										} else if (data = -2) {
											layer.msg('使用者名稱重複')
										} else {
											layer.msg('編輯失敗')
										}
									})
								},
								cancel : function(index, layero) {
									$("#users")[0].reset()// 重置form
									layer.close(index)
								}
							})
						} else if (layEvent == 'begin') {// 啟用
							layer.confirm('確定啟用嗎???', {
								icon : 3,
								title : '提示'
							}, function(index) {
								$.getJSON(path
										+ '/sy/userAction_eidtStatu.action', {
									user_id : data.user_id,
									statu : 1
								}, function(data) {
									layer.close(index);
									table.reload('testReload', {
										page : {
											curr : 1
										// 重新從第 1 頁開始
										}
									})
								});
							})
						} else if (layEvent == 'end') {// end//禁用
							layer.confirm('確定禁用嗎???', {
								icon : 3,
								title : '提示'
							}, function(index) {
								$.getJSON(path
										+ '/sy/userAction_eidtStatu.action', {
									user_id : data.user_id,
									statu : 0
								}, function(data) {
									layer.close(index);
									table.reload('testReload', {
										page : {
											curr : 1
										// 重新從第 1 頁開始
										}
									})
								});
							})
						} else if (layEvent == 'del') {// 刪除
							layer.confirm('親親,你確定刪除嗎?', {
								icon : 3,
								title : '提示'
							}, function(index) {
								$.getJSON(
										path + '/sy/userAction_remove.action',
										{
											user_id : data.user_id
										}, function(data) {
											layer.close(index);
											table.reload('testReload', {
												page : {
													curr : 1
												// 重新從第 1 頁開始
												}
											})
										});
							})
						}
					});
				});

/**
 * 搜尋下拉框角色載入
 */
function part() {
	$.ajaxSettings.async = false
	$.getJSON(path + '/sy/partAction_select.action', {}, function(data) {
		var html = "<option value=''>直接選擇或搜尋選擇</option>";
		// 返回處理的方法
		$.each(data, function(index, item) {
			html += "<option value=" + item.part_id + ">" + item.part_name
					+ "</option>";
		});
		$('#user_part_id').html(html);
		$('#user_part_ids').html(html);
	})
}

part();

配置檔案

pop.xml

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.xyx</groupId>
  <artifactId>xyx_layui1</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>xyx_layui1 Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
  
    
    
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    
   <!--servlet依賴 -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
			<scope>provided</scope>
		</dependency>

		<!-- mySql 依賴 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.44</version>
		</dependency>


		<!-- 引用struts2框架核心依賴 -->
		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-core</artifactId>
			<version>2.5.16</version>
		</dependency>

		<!-- hutoll工具包 -->
		<dependency>
			<groupId>cn.hutool</groupId>
			<artifactId>hutool-all</artifactId>
			<version>4.5.16</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.47</version>
		</dependency>
	
	
  </dependencies>
  <build>
    <finalName>xyx_layui1</finalName>
    <plugins>
    	<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.7.0</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
    </plugins>
  </build>
</project>

web.xml

<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_3_1.xsd"
         version="3.1">
  <display-name>Archetype Created Web Application</display-name>
  
  
  <filter>
 	<filter-name>EncodingFiter</filter-name>
 	<filter-class>com.util.EncodingFiter</filter-class>
 </filter>
 <filter-mapping>
 	<filter-name>EncodingFiter</filter-name>
 	<url-pattern>/*</url-pattern>
 </filter-mapping>
 
 
  <filter>
  	<filter-name>struts2</filter-name>
  	<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  <filter-mapping>
  	<filter-name>struts2</filter-name>
  	<url-pattern>*.action</url-pattern>
  </filter-mapping>
  
  
</web-app>

struts-sy.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
	"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
	<!-- 多了一個包的概念,區分分類 -->
		<package name="sy" extends="base" namespace="/sy">
			<!-- 資料的增刪改 -->
			<action name="/strutsClassAction_*" class="com.web.ClazzAction" method="{1}"></action>
			
			<!-- 使用者 -->
			<action name="/userAction_*" class="com.web.UserAction" method="{1}"></action>
			
		</package>

</struts>

頁面展示

在這裡插入圖片描述

在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述

相關文章