Layui实现CURD完整案例

目录

  • Layui增、删、查、改
  • 盘点用Layui踩过的那些坑

Layui增、删、查、改

今天我们就来讲一下用Layui实现增、删、查、改操作

首先来上一下前端代码
这里关于引入layui官方包就略了 上篇博客有讲过到。
老规矩,首先我们在项目中需要引入 layui 的 js.css ,在这里我把它写成一个通用的,不然我们在项目中每次都要写一样的比较麻烦。

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

//注意这里 ,你们需要引入自己的相关路径



jsp代码,相对应的注释,代码里都有

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



Insert title here



//在这里我把所要写的js都封装了 ,在这里引入对应的Js路径

效果图:
Layui实现CURD完整案例_第1张图片
接下来贴上所要用到的js代码。

//执行渲染
layui.use(['table','layer','form'],function(){
	var data=document.getElementById("sj").value;
	var table =layui.table;
	var layer=layui.layer;
	var form = layui.form;
     /*展示数据表格  */
	table.render({
		  elem:'#test'//表格id
		,url:data+'/booktypeAction.action?methodName=list'//所对应调用的接口
		,method:'post'		//提交方式
	    ,cols:[[
	    	/*根据数据库的表格所对应的名称  */
	         {field:'booktypeid',height:80, width:300, title: '书籍类别序号', sort: true}
	         ,{field:'booktypename', height:80,width:300, title: '书籍类别名称'}
	         ,{field:'createtime',height:80, width:300, title: '当前时间',templet:"
{{layui.util.toDateString(d.createtime, 'yyyy-MM-dd HH:mm:ss')}}
"} ,{field:'right',height:80, width:300, title: '操作', toolbar:'#lineBtns'}//操作栏 ]] ,page:'true'//分页 , id: 'testReload' }); //上方菜单操作栏(查询、以及 增加 按钮 ) var $ = layui.$, active = { //查询 reload: function () { var booktypename = $('#booktypename');//书籍类别名称 根据 id来取值 console.log(booktypename.val()); // 执行重载 table.reload('testReload', { page: { curr: 1 // 重新从第 1 页开始 }, where: { key: 'booktypename', booktypename: booktypename.val(), } }); }, add: function () { //添加 layer.open({//弹出框 type: 1, title: '添加书本类别', maxmin: true, shadeClose: true, //点击遮罩关闭层 area: ['80%', '80%'], content: $('#box1'), btn: ['确定', '取消'], yes: function (index, layero) {//确定执行函数 console.log(layero); //执行添加方法 $.getJSON(data+"/booktypeAction.action?methodName=addBookType", { booktypename: $("#booktypename1").val(), ///角色名 /* booktypename: $("input[ name='booktypename1']").val(), *///角色名 }, function (data) { /*根据后台返回的参数来进行判断 */ if (data==1) { layer.alert('添加成功', {icon: 1, title: '提示'}, function (i) { layer.close(i); layer.close(index);//关闭弹出层 $("#booktype")[0].reset()//重置form }) table.reload('testReload', {//重载表格 page: { curr: 1 // 重新从第 1 页开始 } }) } else if(data==2){ layer.msg('添加失败,请勿重复添加书本类别名称') } }) }, cancel: function (index, layero) {//取消 $("#booktype")[0].reset()//重置form 根据id layer.close(index) } }); } } $('.layui-form .layui-btn').on('click', function () { var type = $(this).data('type'); active[type] ? active[type].call(this) : ''; }); /*表格 行内操作(编辑 以及 删除 按钮操作) */ table.on('tool(test)', function(obj){ var data = obj.data; //获得当前行数据 var urlex=document.getElementById("sj").value; var tr=obj.tr//活动当前行tr 的 DOM对象 console.log(data); var layEvent = obj.event; //获得 lay-event 对应的值(也可以是表头的 event 参数对应的值) if(layEvent === 'del'){ //删除 layer.confirm('确定删除吗?',{title:'删除'}, function(index){ //向服务端发送删除指令og $.getJSON(urlex+'/booktypeAction.action?methodName=deleteBookType',{booktypeid:data.booktypeid}, function(ret){ layer.close(index);//关闭弹窗 table.reload('testReload', {//重载表格 page: { curr: 1 // 重新从第 1 页开始 } }) }); layer.close(index); }); } else if(layEvent === 'edit'){ //编辑 layer.open({ type: 1 //Page层类型 ,skin: 'layui-layer-molv' ,area: ['380px', '270px'] ,title: ['编辑书本类别信息','font-size:18px'] ,btn: ['确定', '取消'] ,shadeClose: true ,shade: 0 //遮罩透明度 ,maxmin: true //允许全屏最小化 ,content:$('#box1') //弹窗id ,success:function(layero,index){ $('#booktypeid').val(data.booktypeid); $('#booktypename1').val(data.booktypename); },yes:function(index,layero){ /* $.ajaxSettings.async = false; */ $.getJSON(urlex+'/booktypeAction.action?methodName=updateBookType',{ booktypeid: $('#booktypeid').val(), booktypename: $('#booktypename1').val(), booktypeid: data.booktypeid, },function(data){ //根据后台返回的参数,来进行判断 if(data>0){ layer.alert('编辑成功',{icon:1,title:'提示'},function(i){ layer.close(i); layer.close(index);//关闭弹出层 $("#booktype")[0].reset()//重置form }) table.reload('testReload',{//重载表格 page:{ curr:1 } }) } }); } }); } }); });

接下来再贴上后台代码
Dao层

package com.liuting.dao;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import com.liuting.util.JsonBaseDao;
import com.liuting.util.JsonUtils;
import com.liuting.util.PageBean;
import com.liuting.util.StringUtils;

public class BooktypeDao extends JsonBaseDao{
	
	/**
	 * 书籍类别查询
	 * @param paMap
	 * @param pageBean
	 * @return
	 * @throws SQLException 
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 */
	public List> list(Map paMap,PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
		String sql=" select * from booktype where true";
		String booktypeid=JsonUtils.getParamVal(paMap, "booktypeid");
		String booktypename=JsonUtils.getParamVal(paMap, "booktypename");
		if(StringUtils.isNotBlank(booktypeid)) {
			sql+=" and booktypeid ="+booktypeid+" ";
		}
		if(StringUtils.isNotBlank(booktypename)) {
			/*ql+=" and booktypename  = '"+booktypename+"' ";*/
			sql+=" and booktypename like '%"+booktypename+"%'";
		}
		sql += "  order by booktypeid desc ";
		return executeQuery(sql, pageBean);
	}
	/**
	 * 增加书本类
	 * @throws SQLException 
	 * @throws IllegalAccessException 
	 * @throws IllegalArgumentException 
	 * @throws SecurityException 
	 * @throws NoSuchFieldException 
	 */
	public int addBookType(Map paMap) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
		String sql="insert into booktype (booktypename,typedescribe) values(?,?)";
		return executeUpdate(sql, new String[] {"booktypename","typedescribe"}, paMap);
		
	}
	
	/**
	 * 删除书本类型
	 * @param paMap
	 * @return
	 * @throws SQLException 
	 * @throws IllegalAccessException 
	 * @throws IllegalArgumentException 
	 * @throws SecurityException 
	 * @throws NoSuchFieldException 
	 */
	public int deleteBookType(Map paMap) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
		String sql="delete from booktype where booktypeid=?";
		return executeUpdate(sql, new String[] {"booktypeid"}, paMap);
	}
	
	/**
	 * 修改书本类型信息
	 * @param paMap
	 * @return
	 * @throws NoSuchFieldException
	 * @throws SecurityException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws SQLException
	 */
	public int updateBookType(Map paMap) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
		String sql="update  booktype set booktypename=?,typedescribe=? where booktypeid=?";
		return executeUpdate(sql, new String[] {"booktypename","typedescribe","booktypeid"}, paMap);
	}
}

web层

package com.liuting.web;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.liuting.dao.BooktypeDao;
import com.liuting.framework.ActionSupport;
import com.liuting.util.PageBean;
import com.liuting.util.ResponseUtil;

public class BooktypeAction extends ActionSupport {
	private BooktypeDao booktypeDao=new BooktypeDao();
	
	/**
	 * 查询书籍类别
	 * @param req
	 * @param resp
	 * @return
	 * @throws Exception
	 */
	public String list(HttpServletRequest req,HttpServletResponse resp) throws Exception {
		try {
			PageBean pageBean=new PageBean();
			pageBean.setRequest(req);
			List> list = this.booktypeDao.list(req.getParameterMap(), pageBean);
			ObjectMapper om =new ObjectMapper();
			Map map=new HashMap<>();
			map.put("code", 0);
			map.put("count", pageBean.getTotal());
			map.put("data", list);
			ResponseUtil.write(resp, om.writeValueAsString(map));
		} catch (InstantiationException e) {
			e.printStackTrace();
		} 
		return null;
	}
	
	
	/**
	 * 增加
	 * @param req
	 * @param resp
	 * @return
	 */
	public String addBookType(HttpServletRequest req,HttpServletResponse resp) {
		try {
			List> list = this.booktypeDao.list(req.getParameterMap(), null);
			int val = 0;
			//如果集合不为空 或者长度等于 0  就把它增加进去 
			if(list==null || list.size() == 0) {
				val = this.booktypeDao.addBookType(req.getParameterMap());
			}
			/*if(list!=null && list.size() >0) {
				val = this.booktypeDao.addBookType(req.getParameterMap());
			}*/
			else {
				val= 2;
			}
			
			ResponseUtil.write(resp, val);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	/**
	 * 删除书本类别
	 * @throws Exception 
	 * @throws JsonProcessingException 
	 * 
	 */

	public String deleteBookType(HttpServletRequest req,HttpServletResponse resp) throws JsonProcessingException, Exception {
		try {
			int deleteBookType=this.booktypeDao.deleteBookType(req.getParameterMap());
			ObjectMapper om=new ObjectMapper();
			ResponseUtil.write(resp, om.writeValueAsString(deleteBookType));
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 修改书籍类别
	 * @param req
	 * @param resp
	 * @return
	 * @throws JsonProcessingException
	 * @throws Exception
	 */
	
	public String updateBookType(HttpServletRequest req,HttpServletResponse resp) throws JsonProcessingException, Exception {
		try {
			int updateBookType=this.booktypeDao.updateBookType(req.getParameterMap());
			ObjectMapper om=new ObjectMapper();
			ResponseUtil.write(resp, om.writeValueAsString(updateBookType));
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	
	
	/**
	 * 下拉框
	 */
	public String listSelect(HttpServletRequest req,HttpServletResponse resp) throws Exception {
		try {
			PageBean pageBean=new PageBean();
			pageBean.setRequest(req);
			List> list = this.booktypeDao.list(req.getParameterMap(), pageBean);
			ObjectMapper om =new ObjectMapper();
			ResponseUtil.write(resp, om.writeValueAsString(list));
		} catch (InstantiationException e) {
			e.printStackTrace();
		} 
		return null;
	}
}

到这里我们的增、删、查、改就完成啦!!!

盘点用Layui踩过的那些坑

① 首先我们在写展示表格的时候,一定要给它写上其lay-filter渲染表格。

②还有就是接口http请求类型,默认:get,有可能我们会遇到乱码的情况,这时候我们只需要改变一下提交方式即可,将method:‘post’,这样就可以解决乱码的问题。

③ 我们在用到官方表单的时候,可能会Select下拉框效果出不来,因为Layui会对select、checkbox、radio等原始元素隐藏,从而进行美化修饰处理。但这需要依赖于form组件,所以你必须加载 form,并且执行一个实例。

var form = layui.form;
form.render('select');

你可能感兴趣的:(Layui实现CURD完整案例)