SpringBoot +Thymeleaf +LayUI2.x 实现增删改查功能

你猜 阅读:671 2021-03-31 13:46:06 评论:0

效果展示:LayUI Table 数据加载功能

LayUI Table 数据检索功能:

LayUI Table 新增

LayUI Table 编辑

LayUI Table 删除

 

LayUI 前端代码:

<!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8"> 
<meta name="viewport" 
	content="width=device-width, initial-scale=1, maximum-scale=1"> 
<title>图书管理系统 - Layui</title> 
<link rel="stylesheet" th:href="@{/css/layui.css}"> 
</head> 
<body class="layui-layout-body"> 
	<div class="layui-layout layui-layout-admin"> 
		<div class="layui-header"> 
			<div class="layui-logo">图书管理系统</div> 
			<ul class="layui-nav layui-layout-right"> 
				<li class="layui-nav-item"><a href="javascript:;"> 超级管理员 </a> 
					<dl class="layui-nav-child"> 
						<dd> 
							<a href="">基本资料</a> 
						</dd> 
						<dd> 
							<a href="">安全设置</a> 
						</dd> 
					</dl></li> 
				<li class="layui-nav-item"><a href="">退了</a></li> 
			</ul> 
		</div> 
 
		<div class="layui-side layui-bg-black"> 
			<div class="layui-side-scroll"> 
				<!-- 左侧导航区域(可配合layui已有的垂直导航) --> 
				<ul class="layui-nav layui-nav-tree" lay-filter="test"> 
					<li class="layui-nav-item layui-nav-itemed"><a class="" 
						href="javascript:;">书籍管理</a> 
						<dl class="layui-nav-child"> 
							<dd> 
								<a href="javascript:;">录入新书</a> 
							</dd> 
							<dd> 
								<a href="javascript:;">新书类别</a> 
							</dd> 
							<dd> 
								<a href="javascript:;">查询书籍</a> 
							</dd> 
						</dl></li> 
					<li class="layui-nav-item"><a href="javascript:;">用户管理</a> 
						<dl class="layui-nav-child"> 
							<dd> 
								<a href="javascript:;">查询用户</a> 
							</dd> 
							<dd> 
								<a href="javascript:;">新增用户</a> 
							</dd> 
						</dl></li> 
					<li class="layui-nav-item"><a href="javascript:;">借阅信息</a> 
						<dl class="layui-nav-child"> 
							<dd> 
								<a href="javascript:;">所有记录</a> 
							</dd> 
							<dd> 
								<a href="javascript:;">个人记录</a> 
							</dd> 
						</dl></li> 
					<li class="layui-nav-item"><a href="">帮助</a></li> 
				</ul> 
			</div> 
		</div> 
 
		<div class="layui-body"> 
			<!-- 内容主体区域 --> 
			<div style="padding: 15px;"> 
			 
				<div class="demoTable"> 
  					搜索名称: 
  					<div class="layui-inline"> 
    					<input class="layui-input" name="id" id="demoReload" autocomplete="off"> 
  					</div> 
  					<button class="layui-btn" data-type="reload">搜索</button> 
				</div> 
				 
				<table id="tb-book" lay-filter="tb-book"></table> 
  
				<script type="text/html" id="barDemo"> 
					<a class="layui-btn layui-btn-xs" lay-event="add">新增</a> 
  					<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a> 
  					<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a> 
				</script> 
				 
				    <!--    编辑弹出层--> 
    		<script type="text/html" id="edit_form"> 
            <div class="layui-col-md10" style="margin-left: 35px;margin-top: 20px"> 
                <form class="layui-form layui-form-pane" lay-filter="edit_form" action=""> 
                    <div class="layui-form-item"> 
                        <label class="layui-form-label">分类名称</label> 
                        <div class="layui-input-block"> 
                            <input type="text" name="categoryName" required  lay-verify="required" placeholder="请输入新的书籍名称" 
                                   autocomplete="off" class="layui-input"> 
                        </div> 
                    </div> 
                    <div class="layui-form-item" style="margin-top: 20px"> 
                        <div class="layui-input-block"> 
                            <button class="layui-btn" lay-submit lay-filter="formDemo">立即提交</button> 
                            <button type="reset" class="layui-btn layui-btn-primary">重置</button> 
                        </div> 
                    </div> 
 
                </form> 
 
            </div> 
    	</script> 
    	  
			</div> 
		</div> 
 
		<div class="layui-footer"> 
			<!-- 底部固定区域 --> 
			© layui.com - 图书管理系统 
		</div> 
		 
		 
	</div> 
	<script th:src="@{/layui.js}"></script> 
	<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> 
	 
	 
	<script> 
	layui.use(['element','table', 'form'], function(){ 
  	  	element = layui.element; 
  	  	table = layui.table; 
  	  	form = layui.form; 
  	  	 
  	  	//第一个实例 
  table.render({ 
    elem: '#tb-book' 
    ,height: 312 
    ,url: '/api/book/category/find'  
    ,where: {categoryId: '', categoryName: ''} 
    ,page: true //开启分页 
    ,cols: [[ //表头 
      {field: 'categoryId', title: 'ID', sort: true, fixed: 'left'} 
      ,{field: 'categoryName', title: '分类名称', } 
      ,{fixed: 'right', title:'操作', toolbar: '#barDemo'} 
    ]] 
  }); 
   
     // 表格数据重载 
    var $ = layui.$, active = { 
    reload: function(){ 
      var demoReload = $('#demoReload'); 
       
      //执行重载 
      table.reload('tb-book', { 
        page: { 
          curr: 1 //重新从第 1 页开始 
        } 
        ,where: { 
            categoryName: demoReload.val() 
        } 
      }, 'data'); 
    } 
  }; 
   
  $('.demoTable .layui-btn').on('click', function(){ 
    var type = $(this).data('type'); 
    active[type] ? active[type].call(this) : ''; 
  }); 
 
   
  //监听工具条 
  table.on('tool(tb-book)', function(obj){ 
    var data = obj.data; 
    if(obj.event === 'add') { 
    	 layer.open({ 
                type: 1, 
                title: '新增类别信息', 
                area: ['420px', '330px'], 
                content: $('#edit_form').html() 
            }); 
            form.on('submit(formDemo)',function(messge){ 
                 console.log(messge.field); 
                 console.log(obj.data); 
                 var str={ 
                                "categoryName":messge.field.categoryName 
                          }; 
                    $.ajax({ 
                            url:"/api/book/category/insert", 
                            type:"POST", 
                            contentType: "application/json; charset=utf-8", 
                            dataType: "json",    
                            data: JSON.stringify(str), 
                            success:function (msg) { 
                                console.log(msg); 
                                // var returnCode = msg.returnValue//取得返回数据(Sting类型的字符串)的信息进行取值判断 
                                if (msg) { 
                                    //layer.closeAll('loading'); 
                                    //layer.load(2); 
                                    layer.msg("修改成功", {icon: 6}); 
                                  	layer.closeAll(); 
                                    // 加载层 - 风格 
                                } else { 
                                    layer.msg("新增失败", {icon: 5}); 
                                } 
                            } 
                        }) 
                        return false;//阻止表单跳转,网页url不显示提交的参数。 
                    }) 
          
    } else if(obj.event === 'del'){ 
      layer.confirm('真的删除行么', function(index){ 
        obj.del(); 
        layer.close(index); 
         
         $.ajax({ 
                            url:"/api/book/category/delete/"+data.categoryId, 
                            type:"DELETE", 
                            success:function (msg) { 
                                console.log(msg); 
                                // var returnCode = msg.returnValue//取得返回数据(Sting类型的字符串)的信息进行取值判断 
                                if (msg) { 
                                    //layer.closeAll('loading'); 
                                    //layer.load(2); 
                                    layer.msg("修改成功", {icon: 6}); 
                                  	layer.closeAll(); 
                                    // 加载层 - 风格 
                                } else { 
                                    layer.msg("新增失败", {icon: 5}); 
                                } 
                            } 
                        }) 
     
      }); 
    } else if(obj.event === 'edit'){ 
      layer.alert('编辑行:<br>'+ JSON.stringify(data)) 
       
      layer.open({ 
            title:'编辑类别信息', 
            type:1, 
            area:['420px','330px'], 
            content:$('#edit_form').html() 
       }) 
       form.render()//更新渲染表单 
       form.val('edit_form',{ 
                //填充表单 
               categoryName:data.categoryName 
       }) 
        
        //提交编辑表单 
        form.on('submit(formDemo)',function(messge){ 
                 console.log(messge.field); 
                 console.log(obj.data); 
                 var str={ 
                                "categoryId":data.categoryId, 
                                "categoryName":messge.field.categoryName 
                            }; 
                    $.ajax({ 
                            url:"/api/book/category/update", 
                            type:"POST", 
                            contentType: "application/json; charset=utf-8", 
                            dataType: "json",    
                            data: JSON.stringify(str), 
                            success:function (msg) { 
                                console.log(msg); 
                                // var returnCode = msg.returnValue//取得返回数据(Sting类型的字符串)的信息进行取值判断 
                                if (msg) { 
                                    //layer.closeAll('loading'); 
                                    //layer.load(2); 
                                    layer.msg("修改成功", {icon: 6}); 
                                   
                                    // 加载层 - 风格 
                                } else { 
                                    layer.msg("修改失败", {icon: 5}); 
                                } 
                            } 
                        }) 
                        return false;//阻止表单跳转,网页url不显示提交的参数。 
                    }) 
        
    } 
     
  
  }); 
   
	}); 
</script> 
</body> 
</html>

 后端代码:

SpringBoot程序入口:

package com.zzg.teach; 
 
import org.mybatis.spring.annotation.MapperScan; 
import org.springframework.boot.SpringApplication; 
import org.springframework.boot.autoconfigure.SpringBootApplication; 
import org.springframework.transaction.annotation.EnableTransactionManagement; 
 
@SpringBootApplication 
@EnableTransactionManagement 
@MapperScan("com.zzg.teach.mapper") 
public class Application{ 
 
	public static void main(String[] args) { 
		// TODO Auto-generated method stub 
		SpringApplication.run(Application.class, args); 
		System.out.println("============= SpringBoot activiti Service Start Success ============="); 
	} 
	 
} 
 

domain:

package com.zzg.teach.domain; 
 
public class BookCatrgory { 
    private String categoryId; 
 
    private String categoryName; 
 
    public String getCategoryId() { 
        return categoryId; 
    } 
 
    public void setCategoryId(String categoryId) { 
        this.categoryId = categoryId == null ? null : categoryId.trim(); 
    } 
 
    public String getCategoryName() { 
        return categoryName; 
    } 
 
    public void setCategoryName(String categoryName) { 
        this.categoryName = categoryName == null ? null : categoryName.trim(); 
    } 
}

mapper:

package com.zzg.teach.mapper; 
 
import java.util.List; 
import java.util.Map; 
 
import com.zzg.teach.domain.BookCatrgory; 
 
public interface BookCatrgoryMapper { 
    int deleteByPrimaryKey(String categoryId); 
 
    int insert(BookCatrgory record); 
 
    int insertSelective(BookCatrgory record); 
 
    BookCatrgory selectByPrimaryKey(String categoryId); 
 
    int updateByPrimaryKeySelective(BookCatrgory record); 
 
    int updateByPrimaryKey(BookCatrgory record); 
     
    // 方法添加 
    List<BookCatrgory> selectAll(Map<String,Object> paramter); 
}

service:

package com.zzg.teach.service; 
 
import java.util.List; 
import java.util.Map; 
 
import com.zzg.jreport.common.BaseService; 
import com.zzg.jreport.common.page.PageData; 
import com.zzg.jreport.common.page.PageParam; 
import com.zzg.teach.domain.BookCatrgory; 
 
public interface BookCatrgoryService extends BaseService<BookCatrgory>{ 
	 // 方法梳理 
    List<BookCatrgory> selectAll(Map<String, Object> paramter); 
     
    PageData<BookCatrgory> selectAllPage(Map<String,Object> parame, PageParam rb); 
} 

seviceImpl:

package com.zzg.teach.service.impl; 
 
import java.util.List; 
import java.util.Map; 
import java.util.UUID; 
import org.apache.commons.lang3.StringUtils; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Service; 
import org.springframework.transaction.annotation.Isolation; 
import org.springframework.transaction.annotation.Propagation; 
import org.springframework.transaction.annotation.Transactional; 
import com.github.pagehelper.PageHelper; 
import com.github.pagehelper.PageInfo; 
import com.zzg.jreport.common.page.PageData; 
import com.zzg.jreport.common.page.PageParam; 
import com.zzg.teach.domain.BookCatrgory; 
import com.zzg.teach.mapper.BookCatrgoryMapper; 
import com.zzg.teach.service.BookCatrgoryService; 
 
@Service 
@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class) 
public class BookCatrgoryServiceImpl implements BookCatrgoryService { 
	@Autowired 
	private BookCatrgoryMapper mapper; 
	@Override 
	public Long insert(BookCatrgory entity) { 
		// TODO Auto-generated method stub 
		if(StringUtils.isEmpty(entity.getCategoryId())) { 
			String uuid = UUID.randomUUID().toString(); 
			entity.setCategoryId(StringUtils.remove(uuid, '-')); 
		} 
		Integer num = mapper.insertSelective(entity); 
		return Long.valueOf(num); 
	} 
 
	@Override 
	public void updateByPrimaryKeySelective(BookCatrgory entity) { 
		// TODO Auto-generated method stub 
		mapper.updateByPrimaryKeySelective(entity); 
	} 
 
	@Override 
	public BookCatrgory selectByPrimaryKey(String sid) { 
		// TODO Auto-generated method stub 
		return mapper.selectByPrimaryKey(sid); 
	} 
 
	@Override 
	public void deleteByPrimaryKey(String sid) { 
		// TODO Auto-generated method stub 
		mapper.deleteByPrimaryKey(sid); 
	} 
 
	@Override 
	public List<BookCatrgory> selectAll(Map<String, Object> paramter) { 
		// TODO Auto-generated method stub 
		return mapper.selectAll(paramter); 
	} 
 
	@Override 
	public PageData<BookCatrgory> selectAllPage(Map<String, Object> parame, PageParam rb) { 
		// TODO Auto-generated method stub 
		PageData<BookCatrgory> pageData = new PageData<BookCatrgory>(); 
 
		PageHelper.startPage(rb.getPageNo(), rb.getLimit()); 
		List<BookCatrgory> rs = mapper.selectAll(parame); 
 
		PageInfo<BookCatrgory> pageInfo = new PageInfo<BookCatrgory>(rs); 
		pageData.setData(pageInfo.getList()); 
		pageData.setPageNum(pageInfo.getPageNum()); 
		pageData.setPageSize(pageInfo.getPageSize()); 
		pageData.setTotalCount(pageInfo.getTotal()); 
		return pageData; 
	} 
 
} 

controller:

package com.zzg.teach.controller; 
 
import java.util.HashMap; 
import java.util.List; 
import java.util.Map; 
 
import org.apache.commons.lang3.StringUtils; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Controller; 
import org.springframework.web.bind.annotation.PathVariable; 
import org.springframework.web.bind.annotation.RequestBody; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 
import org.springframework.web.bind.annotation.RequestParam; 
import org.springframework.web.bind.annotation.ResponseBody; 
 
import com.alibaba.fastjson.JSONObject; 
import com.zzg.jreport.common.controller.AbstractController; 
import com.zzg.jreport.common.page.PageData; 
import com.zzg.jreport.common.page.PageParam; 
import com.zzg.jreport.response.JreportResponse; 
import com.zzg.teach.domain.Book; 
import com.zzg.teach.domain.BookCatrgory; 
import com.zzg.teach.service.BookCatrgoryService; 
 
import io.swagger.annotations.Api; 
import io.swagger.annotations.ApiImplicitParam; 
import io.swagger.annotations.ApiImplicitParams; 
import io.swagger.annotations.ApiOperation; 
import io.swagger.annotations.ApiParam; 
 
@Controller 
@RequestMapping("/api/book/category") 
@Api(value = "书籍类别Controlle", tags = "书籍类别操作服务") 
public class BookCatrgoryController extends AbstractController { 
	@Autowired 
	private BookCatrgoryService service; 
	 
	@ApiOperation(httpMethod = "POST", value = "用户对象保存") 
	@RequestMapping(value = "/insert", method = { RequestMethod.POST }, produces = "application/json;charset=UTF-8") 
	@ResponseBody 
	public JreportResponse insert( 
			@RequestBody @ApiParam(name = "用户对象", value = "json格式对象", required = true)  BookCatrgory entity) { 
		Long engSid = service.insert(entity); 
		return JreportResponse.ok(engSid); 
		 
	} 
	 
	@ApiOperation(httpMethod = "POST", value = "用户对象删除") 
	@RequestMapping(value = "/delete/{categoryId}", method = { RequestMethod.DELETE }, produces = "application/json;charset=UTF-8") 
	@ResponseBody 
	public JreportResponse delete( 
			@PathVariable String categoryId) { 
		service.deleteByPrimaryKey(categoryId); 
		return JreportResponse.ok(); 
		 
	} 
	 
	@ApiOperation(httpMethod = "POST", value = "用户对象更新") 
	@RequestMapping(value = "/update", method = { RequestMethod.POST }, produces = "application/json;charset=UTF-8") 
	@ResponseBody 
	public JreportResponse update( 
			@RequestBody @ApiParam(name = "用户对象", value = "json格式对象", required = true)  BookCatrgory entity) { 
		service.updateByPrimaryKeySelective(entity); 
		return JreportResponse.ok(); 
	} 
	 
	@RequestMapping(value="/find", method={RequestMethod.GET}, produces = "application/json;charset=UTF-8") 
	@ResponseBody 
	@ApiOperation(httpMethod = "GET", value = "新宿分类查询") 
	@ApiImplicitParams({ 
		@ApiImplicitParam(name = "categoryId", value = "主键", required = false, dataType = "Integer", paramType = "query"), 
		@ApiImplicitParam(name = "categoryName", value = "分类名称", required = false, dataType = "String", paramType = "query") 
	}) 
	public String find(@RequestParam String categoryId, @RequestParam String categoryName) { 
		JSONObject obj = new JSONObject(); 
		Map<String, Object> param = new HashMap<String,Object>(); 
		if(!StringUtils.isEmpty(categoryId)) { 
			param.put("categoryId", categoryId); 
		} 
		if(!StringUtils.isEmpty(categoryName)) { 
			param.put("categoryName", categoryName); 
		} 
		List< BookCatrgory> list = service.selectAll(param); 
		obj.put("code", 0); 
		obj.put("data", list); 
		return obj.toJSONString(); 
	} 
	 
	 
	@RequestMapping(value="/findByPage", method={RequestMethod.POST}, produces = "application/json;charset=UTF-8") 
	@ResponseBody 
	@ApiOperation(httpMethod = "POST", value = "用户分页查询") 
	@ApiImplicitParams({ 
		@ApiImplicitParam(name = "id", value = "主键", required = false, dataType = "Integer", paramType = "query"), 
		@ApiImplicitParam(name = "username", value = "用户名称", required = false, dataType = "String", paramType = "query"), 
		@ApiImplicitParam(name = "email", value = "用户邮箱", required = false, dataType = "String", paramType = "query"), 
		@ApiImplicitParam(name = "isStaff", value = "是否在职:1 在职、2:离职", required = false, dataType = "Integer", paramType = "query"), 
		@ApiImplicitParam(name = "isActive", value = "激活状态:1 已激活、2:未激活", required = false, dataType = "Integer", paramType = "query") 
	}) 
	public JreportResponse findByPage(@RequestBody @ApiParam(name = "用户对象", value = "json格式对象", required = true) JSONObject entity) { 
 
		Map<String, Object> param = JSONObject.toJavaObject(entity, Map.class); 
		PageParam rb = super.initPageBounds(param); 
		PageData< BookCatrgory> pageList = service.selectAllPage(param, rb); 
		return JreportResponse.ok(pageList); 
	} 
	 
	 
	 
 
} 

mapper.xml 配置文件:

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 
<mapper namespace="com.zzg.teach.mapper.BookCatrgoryMapper"> 
  <resultMap id="BaseResultMap" type="com.zzg.teach.domain.BookCatrgory"> 
    <id column="category_id" jdbcType="VARCHAR" property="categoryId" /> 
    <result column="category_name" jdbcType="VARCHAR" property="categoryName" /> 
  </resultMap> 
  <sql id="Base_Column_List"> 
    category_id, category_name 
  </sql> 
   
  <!-- 公共查询条件  --> 
  <sql id="condition"> 
  		<if test="categoryId != null and categoryId !=''"> 
  			and category_id = #{categoryId} 
  		</if> 
  		<if test="categoryName != null and categoryName !=''"> 
  			and category_name LIKE CONCAT('%',#{categoryName},'%') 
  		</if> 
  </sql> 
   
   <!-- 方法梳理 --> 
  <select id="selectAll" parameterType="java.util.Map" resultMap="BaseResultMap"> 
		select 
		<include refid="Base_Column_List" /> 
		from book_catrgory 
		where 1 = 1 
		<include refid="condition"></include> 
  </select> 
   
  <select id="selectByPrimaryKey" parameterType="java.lang.String" resultMap="BaseResultMap"> 
    select  
    <include refid="Base_Column_List" /> 
    from book_catrgory 
    where category_id = #{categoryId,jdbcType=VARCHAR} 
  </select> 
  <delete id="deleteByPrimaryKey" parameterType="java.lang.String"> 
    delete from book_catrgory 
    where category_id = #{categoryId,jdbcType=VARCHAR} 
  </delete> 
  <insert id="insert" parameterType="com.zzg.teach.domain.BookCatrgory"> 
    insert into book_catrgory (category_id, category_name) 
    values (#{categoryId,jdbcType=VARCHAR}, #{categoryName,jdbcType=VARCHAR}) 
  </insert> 
  <insert id="insertSelective" parameterType="com.zzg.teach.domain.BookCatrgory"> 
    insert into book_catrgory 
    <trim prefix="(" suffix=")" suffixOverrides=","> 
      <if test="categoryId != null"> 
        category_id, 
      </if> 
      <if test="categoryName != null"> 
        category_name, 
      </if> 
    </trim> 
    <trim prefix="values (" suffix=")" suffixOverrides=","> 
      <if test="categoryId != null"> 
        #{categoryId,jdbcType=VARCHAR}, 
      </if> 
      <if test="categoryName != null"> 
        #{categoryName,jdbcType=VARCHAR}, 
      </if> 
    </trim> 
  </insert> 
  <update id="updateByPrimaryKeySelective" parameterType="com.zzg.teach.domain.BookCatrgory"> 
    update book_catrgory 
    <set> 
      <if test="categoryName != null"> 
        category_name = #{categoryName,jdbcType=VARCHAR}, 
      </if> 
    </set> 
    where category_id = #{categoryId,jdbcType=VARCHAR} 
  </update> 
  <update id="updateByPrimaryKey" parameterType="com.zzg.teach.domain.BookCatrgory"> 
    update book_catrgory 
    set category_name = #{categoryName,jdbcType=VARCHAR} 
    where category_id = #{categoryId,jdbcType=VARCHAR} 
  </update> 
</mapper>

整体项目代码会在最近几天完整发布,并提供源码下载地址

标签:Spring Boot
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号