LayUi_2(SSM+LayUi增删改查分页条件查询简单Demo)

版权声明:本文为博主原创文章,未经博主允许不得转载

项目在Idea整体轮廓

在这里插入图片描述
在这里插入图片描述

1.Car.java

```package com.mr.model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Car {
    private Integer carId;
    private String carName;
    private String carPrice;
}

2.CarVo.java

package com.mr.vo;

import com.mr.model.Car;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@AllArgsConstructor
@Data
@NoArgsConstructor
public class CarVo extends Car {
    // 车辆起始价格
    private String carStartPrice;
    // 车辆结束价格
    private String carEndPrice;
}

3.LayUiController.java

package com.mr.controller;

import com.github.pagehelper.PageInfo;
import com.mr.model.Car;
import com.mr.service.ILayUiService;


import com.mr.util.DataGridVo;
import com.mr.util.Page;
import com.mr.vo.CarVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;


/**
 *
 */
@Controller
@RequestMapping("LayUi")
public class LayUiController {
    @Autowired
    private ILayUiService layUiService;

    /**
     * 查询
     * @param
     * @return
     */
  /*  @RequestMapping("queryCar")
    @ResponseBody
    public DataGridVo<Car> queryCar(Page page){
        List<Car> cars=layUiService.queryCar(page);
        PageInfo<Car> pageCar = new PageInfo<Car>(cars);
        DataGridVo<Car> car = new DataGridVo<Car>(0,"",pageCar.getTotal(),pageCar.getList());
        return car;
    }*/

    /**
     * 查询+分页
     * @param
     * @return
     *//*
    @RequestMapping("queryCar")
    @ResponseBody
    public LayResult<Car> queryCar(Page page){
        return layUiService.queryCar(page);
    }*/
    /**
     * 查询+分页+条件查询
     */
    @RequestMapping("queryCar")
    @ResponseBody
    public DataGridVo<Car> queryCar(Page page, CarVo vo){
        PageInfo<Car> pageList = layUiService.queryCar(page,vo);
        DataGridVo<Car> pageVo = new DataGridVo<Car>();
        pageVo.setCount(pageList.getTotal());
        pageVo.setData(pageList.getList());
        return pageVo;
    }
    /**
     * 新增
     */
    @RequestMapping("addCar")
    @ResponseBody
    public String addCar(Car car){
        layUiService.addCar(car);
        return "新增成功";
    }
    /**
     * 删除
     */
    @RequestMapping("deleteCar")
    @ResponseBody
    public String  deleteCar(Integer id){
      layUiService.deleteCar(id);
       return "删除成功";
    }
    /**
     * 根据Id回显一条数据
     */
    @RequestMapping("selectByCarId")
    @ResponseBody
    public ModelAndView selectByCarId(Integer id){
       Car car  =  layUiService.selectByCarId(id);
        ModelAndView modelAndView = new ModelAndView("../../Ui/update");
        modelAndView.addObject("car",car);
        return modelAndView ;


    }
    /**
     * 修改
     *
     */
    @ResponseBody
    @RequestMapping("updateCar")
    public String updateStudent(Car car){
        try {
            layUiService.updateCar(car);
            return "ok";
        }catch (Exception e){
            e.printStackTrace();
            return "error";
        }
    }

}``

4.ILayUiService.java


import com.github.pagehelper.PageInfo;
import com.mr.model.Car;
import com.mr.util.LayResult;
import com.mr.util.Page;
import com.mr.vo.CarVo;


/**
 *
 */
public interface ILayUiService {
    /**
     * 查询+分页
     * @param
     * @return
     */
    //LayResult<Car> queryCar(Page page);

    /**
     * 新增
     */
    void addCar(Car car);

    /**
     * 删除
     * @param id
     */
    void deleteCar(Integer id);

    /**
     * 根据Id回显一条数据
     */
    Car selectByCarId(Integer id);

    /**
     * 修改
     * @param car
     */
    void updateCar(Car car);

    /**
     * 查询+分页+条件查询
     */
    PageInfo<Car> queryCar(Page page, CarVo vo);


/**
 * 查询
 * @param
 * @return
 */
    // List<Car> queryCar(Page page);


}

5.LayUiServiceImpl.java


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mr.mapper.LayUiMapper;
import com.mr.model.Car;
import com.mr.service.ILayUiService;
import com.mr.util.LayResult;
import com.mr.util.Page;
import com.mr.vo.CarVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * 
 */
@Service(value="layUiService")
public class LayUiServiceImpl implements ILayUiService{
    @Autowired
    private LayUiMapper layUiMapper;

    /**
     * 查询
     * @param
     * @return
     */
   /* public List<Car> queryCar(Page page) {
        return layUiMapper.queryCar();
    }*/
    /**
     * 查询+分页
     * @param
     * @return
     */
    /*public LayResult<Car> queryCar(Page page) {
        if(page==null){
            page=new Page();
        }
        PageHelper.startPage(page.getPage(),page.getLimit());
        List<Car> cars = layUiMapper.queryCar();
        PageInfo<Car> info = new PageInfo<Car>(cars);
        LayResult<Car> carLayResult = new LayResult<Car>();
        carLayResult.setCode(0);
        carLayResult.setCount(info.getTotal());
        carLayResult.setData(info.getList());
        return  carLayResult;
    }*/

    /**
     * 新增
     */
    public void addCar(Car car) {
        layUiMapper.addCar(car);
    }

    /**
     * 删除
     * @param
     */
    public void deleteCar(Integer id) {
        layUiMapper.deleteCar(id);
    }

    /**
     * 根据Id回显一条数据
     * @param id
     * @return
     */
    public Car selectByCarId(Integer id) {
        return layUiMapper.selectByCarId(id);
    }

    public void updateCar(Car car) {
        layUiMapper.updateCar(car);
    }

    /**
     * 查询+分页+条件查询
     *
     *
     */
    public PageInfo<Car> queryCar(Page page, CarVo vo) {
        if(page ==null){
            page   = new Page();
        }

        PageHelper.startPage(page.getPage(),page.getLimit());

        List<Car> list = layUiMapper.queryCar(vo);
        PageInfo<Car> pageList  = new PageInfo<Car>(list);
        return pageList;
    }


}

6.LayUiMapper.java


import com.mr.model.Car;
import com.mr.vo.CarVo;
import org.apache.ibatis.annotations.Param;

import java.util.List;

/**
 * 
 */
public interface LayUiMapper {
    /**
     * 查询+分页
     * @param
     * @return
     */
   // List<Car> queryCar();

    /**
     * 新增
     * @param
     */
    void addCar(Car car);

    /**
     * 删除
     * @param
     */
    void deleteCar(Integer id);

    /**
     * 根据Id回显一条数据
     * @param id
     * @return
     */
    Car selectByCarId(Integer id);

    //修改
    void updateCar(Car car);

    /**
     * 查询+分页+条件查询
     *
     *
     */
    List<Car> queryCar(@Param("cars") CarVo vo);


    /**
     * 查询
     * @param
     * @return
     */
    //List<Car> queryCar();
}

7.LayUiMapper.XML

<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mr.mapper.LayUiMapper">
    <!--查询+分页-->
<!--List<Car> queryCar();-->
    <!--<select id="queryCar" resultType="car">
        select car_id,car_name,car_price from t_car

    </select>-->
    <!-- /**
     * 新增
     * @param
     */
    void addCar(Car car);-->
    <insert id="addCar" parameterType="car">
        insert into t_car(car_name,car_price)values(#{carName},#{carPrice})
    </insert>
    <!--删除-->
    <!-- void deleteCar(Integer id);-->
    <delete id="deleteCar" parameterType="int">
        delete from t_car where car_id=#{carId}
    </delete>
    <!-- /**
     * 根据Id回显一条数据
     * @param id
     * @return
     */
    Car selectByCarId(Integer id);-->
    <select id="selectByCarId" parameterType="int" resultType="car">
        select car_id,car_name,car_price from t_car where car_id=#{carId}
    </select>
    <!-- //修改
    void updateCar(Car car);-->
    <update id="updateCar" parameterType="car">
          update t_car
          set car_name=#{carName},
          car_price=#{carPrice}
           where car_id=#{carId}
    </update>
    <!-- /**
     * 查询+分页+条件查询
     *
     *
     */
    List<Car> queryCar(@Param("car") CarVo vo);
-->
    <select id="queryCar" resultType="car" >
      select car_id,car_name,car_price from t_car
        <where>
            <if test="cars.carName!=null and cars.carName!=''">
                and car_name like CONCAT("%",#{cars.carName},"%")
            </if>
            <if test="cars.carStartPrice!=null and cars.carStartPrice!=''">
                and car_price &gt;=#{cars.carStartPrice}
            </if>
            <if test="cars.carEndPrice!=null and cars.carEndPrice!=''">
                and car_price &lt;=#{cars.carEndPrice}
            </if>
        </where>
    </select>


</mapper> 

8.index.jsp

  Created by IntelliJ IDEA.
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="<%=request.getContextPath()%>/js/jquery-1.11.3.min.js"></script>
    <link rel="stylesheet" href="<%=request.getContextPath()%>/layui/css/layui.css">
    <script src="<%=request.getContextPath()%>/layui/layui.js"></script>
</head>
<body class="layui-layout-body">

<div class="layui-layout layui-layout-admin">
    <div class="layui-header">
        <div class="layui-logo">Hello LayUi</div>
        <!-- 头部区域(可配合layui已有的水平导航) -->
        <ul class="layui-nav layui-layout-left">
            <li class="layui-nav-item"><a href="">控制台</a></li>
            <li class="layui-nav-item"><a href="">商品管理</a></li>
            <li class="layui-nav-item"><a href="">用户</a></li>
            <li class="layui-nav-item">
                <a href="javascript:;">其它系统</a>
                <dl class="layui-nav-child">
                    <dd><a href="">邮件管理</a></dd>
                    <dd><a href="">消息管理</a></dd>
                    <dd><a href="">授权管理</a></dd>
                </dl>
            </li>
        </ul>
        <ul class="layui-nav layui-layout-right">
            <li class="layui-nav-item">
                <a href="javascript:;">
                    <img src="http://t.cn/RCzsdCq" class="layui-nav-img">
                    贤心
                </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>
<div class="layui-tab layui-tab-card site-demo-button" style="position: relative;">
    <ul class="layui-nav layui-nav-tree layui-nav-side" style="padding-top: 60px">
        <li class="layui-nav-item layui-nav-itemed">
            <a href="javascript:;">默认展开</a>
            <dl class="layui-nav-child">
                <dd>
                    <a href="#" data-url="Ui/list" data-title="选项卡a"  data-id="11" class="site-demo-active" data-type="tabAdd">选项卡a</a>
                </dd>
                <dd>
                    <a href="#" data-url="b" data-title="选项卡b"  data-id="22" class="site-demo-active" data-type="tabAdd">选项卡b</a>
                </dd>
                <dd>
                    <a href="http://www.baidu.com">超链接</a>
                </dd>
            </dl>
        </li>
        <li class="layui-nav-item">
            <a href="javascript:;">解决方案</a>
            <dl class="layui-nav-child">
                <dd>
                    <a href="">移动模块</a>
                </dd>
                <dd>
                    <a href="">后台模版</a>
                </dd>
                <dd>
                    <a href="">电商平台</a>
                </dd>
            </dl>
        </li>
        <li class="layui-nav-item">
            <a href="#" data-url="c" data-title="选项卡c"  data-id="33" class="site-demo-active" data-type="tabAdd">选项卡c</a>
        </li>
        <li class="layui-nav-item">
            <a href="">大数据</a>
        </li>
    </ul>

    <div class="layui-tab" lay-filter="demo" lay-allowclose="true" style="margin-left: 200px;">
        <ul class="layui-tab-title">
        </ul>
        <ul class="rightmenu" style="display: none;position: absolute;">
            <li data-type="closethis">关闭当前</li>
            <li data-type="closeall">关闭所有</li>
        </ul>
        <div class="layui-tab-content"></div>
    </div>
</div>

</body>

<script>
    <!--Tabs选项卡-->
    layui.use('element', function() {
        var $ = layui.jquery;
        var element = layui.element; //Tab的切换功能,切换事件监听等,需要依赖element模块

        //触发事件
        var active = {
            //在这里给active绑定几项事件,后面可通过active调用这些事件
            tabAdd: function(url,id,name) {
                //新增一个Tab项 传入三个参数,分别对应其标题,tab页面的地址,还有一个规定的id,是标签中data-id的属性值
                //关于tabAdd的方法所传入的参数可看layui的开发文档中基础方法部分
                element.tabAdd('demo', {
                    title: name,
                    content: '<iframe data-frameid="'+id+'" scrolling="auto" frameborder="0" src="'+url+'.jsp" style="width:100%;height:99%;"></iframe>',
                    id: id //规定好的id
                })
                CustomRightClick(id); //给tab绑定右击事件
                FrameWH();  //计算ifram层的大小
            },
            tabChange: function(id) {
                //切换到指定Tab项
                element.tabChange('demo', id); //根据传入的id传入到指定的tab项
            },
            tabDelete: function (id) {
                element.tabDelete("demo", id);//删除
            }
            , tabDeleteAll: function (ids) {//删除所有
                $.each(ids, function (i,item) {
                    element.tabDelete("demo", item); //ids是一个数组,里面存放了多个id,调用tabDelete方法分别删除
                })
            }
        };


        //当点击有site-demo-active属性的标签时,即左侧菜单栏中内容 ,触发点击事件
        $('.site-demo-active').on('click', function() {
            var dataid = $(this);

            //这时会判断右侧.layui-tab-title属性下的有lay-id属性的li的数目,即已经打开的tab项数目
            if ($(".layui-tab-title li[lay-id]").length <= 0) {
                //如果比零小,则直接打开新的tab项
                active.tabAdd(dataid.attr("data-url"), dataid.attr("data-id"),dataid.attr("data-title"));
            } else {
                //否则判断该tab项是否以及存在

                var isData = false; //初始化一个标志,为false说明未打开该tab项 为true则说明已有
                $.each($(".layui-tab-title li[lay-id]"), function () {
                    //如果点击左侧菜单栏所传入的id 在右侧tab项中的lay-id属性可以找到,则说明该tab项已经打开
                    if ($(this).attr("lay-id") == dataid.attr("data-id")) {
                        isData = true;
                    }
                })
                if (isData == false) {
                    //标志为false 新增一个tab项
                    active.tabAdd(dataid.attr("data-url"), dataid.attr("data-id"),dataid.attr("data-title"));
                }
            }
            //最后不管是否新增tab,最后都转到要打开的选项页面上
            active.tabChange(dataid.attr("data-id"));
        });

        function CustomRightClick(id) {
            //取消右键  rightmenu属性开始是隐藏的 ,当右击的时候显示,左击的时候隐藏
            $('.layui-tab-title li').on('contextmenu', function () { return false; })
            $('.layui-tab-title,.layui-tab-title li').click(function () {
                $('.rightmenu').hide();
            });
            //桌面点击右击
            $('.layui-tab-title li').on('contextmenu', function (e) {
                var popupmenu = $(".rightmenu");
                popupmenu.find("li").attr("data-id",id); //在右键菜单中的标签绑定id属性

                //判断右侧菜单的位置
                l = ($(document).width() - e.clientX) < popupmenu.width() ? (e.clientX - popupmenu.width()) : e.clientX;
                t = ($(document).height() - e.clientY) < popupmenu.height() ? (e.clientY - popupmenu.height()) : e.clientY;
                popupmenu.css({ left: l, top: t }).show(); //进行绝对定位
                //alert("右键菜单")
                return false;
            });
        }

        $(".rightmenu li").click(function () {

            //右键菜单中的选项被点击之后,判断type的类型,决定关闭所有还是关闭当前。
            if ($(this).attr("data-type") == "closethis") {
                //如果关闭当前,即根据显示右键菜单时所绑定的id,执行tabDelete
                active.tabDelete($(this).attr("data-id"))
            } else if ($(this).attr("data-type") == "closeall") {
                var tabtitle = $(".layui-tab-title li");
                var ids = new Array();
                $.each(tabtitle, function (i) {
                    ids[i] = $(this).attr("lay-id");
                })
                //如果关闭所有 ,即将所有的lay-id放进数组,执行tabDeleteAll
                active.tabDeleteAll(ids);
            }

            $('.rightmenu').hide(); //最后再隐藏右键菜单
        })
        function FrameWH() {
            var h = $(window).height() -41- 10 - 60 -10-44 -10;
            $("iframe").css("height",h+"px");
        }

        $(window).resize(function () {
            FrameWH();
        })
    });
</script>
</body>
</html>

9.list.jsp

  Created by IntelliJ IDEA.
 
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="<%=request.getContextPath()%>/js/jquery-1.11.3.min.js"></script>
    <link rel="stylesheet" href="<%=request.getContextPath()%>/layui/css/layui.css">
    <script src="<%=request.getContextPath()%>/layui/layui.js"></script>
</head>
<body>
<!--条件查询-->
<div class="demoTable">
    车辆名称:
    <div class="layui-inline">
        <input name="carName" class="layui-input" id="carName" autocomplete="off">
    </div>
    <button class="layui-btn" data-type="reload" id="search">检索车辆名称</button>

    车辆起始价格:
    <div class="layui-inline">
        <input name="carStartPrice" class="layui-input" id="carStartPrice" autocomplete="off">
    </div>

    车辆结束价格:
    <div class="layui-inline">
        <input name="carEndPrice" class="layui-input" id="carEndPrice" autocomplete="off">
    </div>

    <button class="layui-btn" data-type="reload" id="search1">检索车辆价格</button>
</div>

<table id="demo" lay-filter="test"></table>


<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="add">新增</button>
        <button class="layui-btn layui-btn-sm" lay-event="update">编辑</button>
    </div>
</script>
<script type="text/html" id="barDemo">
    <button class="layui-btn layui-btn-sm" lay-event="delete">删除</button>
</script>
<script>
    layui.use('table', function(){
        var table = layui.table;
            <!-----------------查询-------------------->
        //第一个实例
        table.render({
            elem: '#demo'
            ,height: 480
            ,url: '<%=request.getContextPath()%>/LayUi/queryCar.do' //数据接口
            ,page: true, //开启分页
            toolbar: '#toolbarDemo'//开启工具栏
            ,even:true
            ,style:'background-color: #5FB878; color: #fff;'
            ,cols: [[ //表头
                ,{type: 'checkbox', fixed: 'left'}
                ,{field: 'carId', title: 'ID', width:300, sort: true, fixed: 'left', totalRowText: '合计:'}
                ,{field: 'carName', title: '车辆名称', width:300}
                ,{field: 'carPrice', title: '车辆价格', width: 300, sort: true, totalRow: true}
                ,{fixed: 'right', width: 320, align:'center', toolbar: '#barDemo'}
            ]]
        });

        <!--条件查询-->
        var $ = layui.$,active={
            reload:function(){
                table.reload('demo',{
                    where:{carName:$("#carName").val(),carStartPrice:$("#carStartPrice").val(),carEndPrice:$("#carEndPrice").val()}
                })
            }
        }

        $('.demoTable .layui-btn').on('click', function(){
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });

        <!-----------------------------------------------新增-------------------------->
        //监听事件
        table.on('toolbar(test)', function(obj){
            var checkStatus = table.checkStatus(obj.config.id),data = checkStatus.data;
            switch(obj.event){
                case 'add':
                    layer.open({
                        type: 2,
                        //skin: 'layui-layer-rim', //加上边框
                        area: ['420px', '240px'], //宽高
                        content:'<%=request.getContextPath()%>/Ui/add.jsp',
                        btn:['确定','取消'],
                        yes:function(index,layero){
                            var formSubmit = layer.getChildFrame('form',index);
                            var submited = formSubmit.find('button')[0];
                            submited.click();
                            location.reload();
                        }
                    });
                    break;
                case 'delete':
                    if(data.length<0){
                        layer.msg('请选择一行删除');
                    }
                    break;
                    <!-------------------打开修改回显页面-------------->
                case 'update':
                    layer.open({
                        type: 2,
                        //skin: 'layui-layer-rim', //加上边框
                        area: ['420px', '240px'], //宽高
                        content:'<%=request.getContextPath()%>/LayUi/selectByCarId.do?id='+data[0].carId,
                        btn:['确定','取消'],
                        yes:function(index,layero){
                            var formSubmit = layer.getChildFrame('form',index);
                            var submited = formSubmit.find('button')[0];
                            submited.click();
                            location.reload();
                        }
                    });
                    break;
            };
        });
        <!--------------删除-------------------------->
        //监听工具条
        table.on('tool(test)', function(obj){ //注:tool是工具条事件名,test是table原始容器的属性 lay-filter="对应的值"
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值(也可以是表头的 event 参数对应的值)
            var tr = obj.tr; //获得当前行 tr 的DOM对象

            if(layEvent === 'delete'){ //删除
                layer.confirm('真的删除行么', function(index){
                    //obj.del();
                    console.log(obj);
                    console.log(data);
                    //layer.close(index);
                    $.ajax({
                        url: "<%=request.getContextPath()%>/LayUi/deleteCar.do",
                        type: "POST",
                        data:{'id':data.carId},
                        dataType: "text",
                        success: function(data){
                            if(data==null){
                                layer.msg("删除失败", {icon: 5});
                            }else{
                                //删除这一行
                                obj.del();
                                //关闭弹框
                                layer.close(index);
                                layer.msg("删除成功", {icon: 6});
                                layer.closeAll();
                                window.location.reload();
                                Load(); //删除完需要加载数据
                            }
                        },
                        error:function(){
                            alert(data);
                        },

                    });
                });
            }
        });




    });


</script>


</body>

</html>

10.add.jsp

  Created by IntelliJ IDEA.
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="<%=request.getContextPath()%>/js/jquery-1.11.3.min.js"></script>
    <link rel="stylesheet" href="<%=request.getContextPath()%>/layui/css/layui.css">
    <script src="<%=request.getContextPath()%>/layui/layui.js"></script>
</head>
<body>

<form class="layui-form" action="/LayUi/addCar.do">


    <div class="layui-form-item layui-form-pane">
        <label class="layui-form-label">车辆名称:</label>
        <div class="layui-input-block">
            <input type="text" name="carName"  required  lay-verify="required" placeholder="请输入车辆名称" autocomplete="off" class="layui-input">
        </div>
    </div>

    <div class="layui-form-item layui-form-pane">
        <label class="layui-form-label">车辆价格:</label>
        <div class="layui-input-block">
            <input type="text" name="carPrice"  required  lay-verify="number" placeholder="请输入车辆价格" autocomplete="off" class="layui-input">
        </div>
    </div>

    <div class="layui-form-item">
        <div class="layui-input-block">
            <!-- 隐藏提交按钮,在父层中调用 -->
            <button id="addDepartment" class="layui-btn" lay-filter="formVerify" lay-submit style="display: none">提交</button>
        </div>
    </div>
</form>
<script>
    layui.use(['form'],function () {
        var form = layui.form;
        form.verify({
            carName: function (value, item) {
                //value:表单的值、item:表单的DOM对象
                if (value.length < 0) {
                    return '车辆名称不能为空';
                }
            },
            carPrice: function (value, item) {
                if (value.length < 0) {
                    return '车辆价格不能为空';
                }
            }

        });

        form.on('submit(formVerify)',function (data) {
            // 提交成功后返回信息,关闭弹出层
            parent.layer.msg('操作成功', {
                icon: 1,
                time: 2000
            });

            //当你在iframe页面关闭自身时
            var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
            parent.layer.close(index);
        });
    });

</script>
</body>
</html>

11.update.jsp

  Created by IntelliJ IDEA.
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="<%=request.getContextPath()%>/js/jquery-1.11.3.min.js"></script>
    <link rel="stylesheet" href="<%=request.getContextPath()%>/layui/css/layui.css">
    <script src="<%=request.getContextPath()%>/layui/layui.js"></script>
</head>
<body>

<form class="layui-form" action="/LayUi/updateCar.do">

    <div class="layui-form-item layui-form-pane">
        <label class="layui-form-label">车辆主键:</label>
        <div class="layui-input-block">
            <input type="text" name="carId"  value="${car.carId}" required  lay-verify="required" placeholder="请输入车辆名称" autocomplete="off" class="layui-input">
        </div>
    </div>

    <div class="layui-form-item layui-form-pane">
        <label class="layui-form-label">车辆名称:</label>
        <div class="layui-input-block">
            <input type="text" name="carName"  value="${car.carName}" required  lay-verify="required" placeholder="请输入车辆名称" autocomplete="off" class="layui-input">
        </div>
    </div>

    <div class="layui-form-item layui-form-pane">
        <label class="layui-form-label">车辆价格:</label>
        <div class="layui-input-block">
            <input type="text" name="carPrice"  value="${car.carPrice}" required  lay-verify="number" placeholder="请输入车辆价格" autocomplete="off" class="layui-input">
        </div>
    </div>

    <div class="layui-form-item">
        <div class="layui-input-block">
            <!-- 隐藏提交按钮,在父层中调用 -->
            <button id="addDepartment" class="layui-btn" lay-filter="formVerify" lay-submit style="display: none">提交</button>
        </div>
    </div>
</form>
<script>
    layui.use(['form'],function () {
        var form = layui.form;
        form.verify({
            carName: function (value, item) {
                //value:表单的值、item:表单的DOM对象
                if (value.length < 0) {
                    return '车辆名称不能为空';
                }
            },
            carPrice: function (value, item) {
                if (value.length < 0) {
                    return '车辆价格不能为空';
                }
            }

        });

        form.on('submit(formVerify)',function (data) {
            // 提交成功后返回信息,关闭弹出层
            parent.layer.msg('操作成功', {
                icon: 1,
                time: 2000
            });

            //当你在iframe页面关闭自身时
            var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
            parent.layer.close(index);
            window.location.reload();
        });
    });

</script>
</body>
</html>



前台效果展示(增删改查+条件查询+分页)

在这里插入图片描述
``

附加:main.jsp

<%--
  Created by IntelliJ IDEA.
 
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <title>layui在线调试</title>
   <%-- <link rel="stylesheet" href="//res.layui.com/layui/dist/css/layui.css?t=1551352891272" media="all">--%>
    <style>
        body{margin: 10px;}
        .demo-carousel{height: 200px; line-height: 200px; text-align: center;}
    </style>
    <link rel="stylesheet" href="<%=request.getContextPath()%>/layui/css/layui.css">
    <script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery-1.11.3.min.js" ></script>
    <script type="text/javascript" src="<%=request.getContextPath()%>/layer/layer.js" ></script>
    <script src="<%=request.getContextPath()%>/layui/layui.js"></script>
</head>
<body>

<table class="layui-hide" id="demo" lay-filter="test"></table>

<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="detail">查看</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>

<div class="layui-tab layui-tab-brief" lay-filter="demo">
    <ul class="layui-tab-title">
        <li class="layui-this">演示说明</li>
        <li>日期</li>
        <li>分页</li>
        <li>上传</li>
        <li>滑块</li>
    </ul>
    <div class="layui-tab-content">
        <div class="layui-tab-item layui-show">

            <div class="layui-carousel" id="test1">
                <div carousel-item>
                    <div><p class="layui-bg-green demo-carousel">在这里,你将以最直观的形式体验 layui!</p></div>
                    <div><p class="layui-bg-red demo-carousel">在编辑器中可以执行 layui 相关的一切代码</p></div>
                    <div><p class="layui-bg-blue demo-carousel">你也可以点击左侧导航针对性地试验我们提供的示例</p></div>
                    <div><p class="layui-bg-orange demo-carousel">如果最左侧的导航的高度超出了你的屏幕</p></div>
                    <div><p class="layui-bg-cyan demo-carousel">你可以将鼠标移入导航区域,然后滑动鼠标滚轮即可</p></div>
                </div>
            </div>
        </div>
        <div class="layui-tab-item">
            <div id="laydateDemo"></div>
        </div>
        <div class="layui-tab-item">
            <div id="pageDemo"></div>
        </div>
        <div class="layui-tab-item">
            <div class="layui-upload-drag" id="uploadDemo">
                <i class="layui-icon"></i>
                <p>点击上传,或将文件拖拽到此处</p>
            </div>
        </div>
        <div class="layui-tab-item">
            <div id="sliderDemo" style="margin: 50px 20px;"></div>
        </div>
    </div>
</div>

<blockquote class="layui-elem-quote layui-quote-nm layui-hide" id="footer">layui {{ layui.v }} 提供强力驱动</blockquote>


<%--<link rel="stylesheet" href="//res.layui.com/layui/dist/layui.js?t=1551352891272" media="all">--%>
<script>
    layui.config({
        version: '1551352891272' //为了更新 js 缓存,可忽略
    });

    layui.use(['laydate', 'laypage', 'layer', 'table', 'carousel', 'upload', 'element', 'slider'], function(){
        var laydate = layui.laydate //日期
            ,laypage = layui.laypage //分页
            ,layer = layui.layer //弹层
            ,table = layui.table //表格
            ,carousel = layui.carousel //轮播
            ,upload = layui.upload //上传
            ,element = layui.element //元素操作
            ,slider = layui.slider //滑块

        //向世界问个好
        layer.msg('Hello World');

        //监听Tab切换
        element.on('tab(demo)', function(data){
            layer.tips('切换了 '+ data.index +':'+ this.innerHTML, this, {
                tips: 1
            });
        });

        //执行一个 table 实例
        table.render({
            elem: '#demo'
            ,height: 420
            ,url: '<%=request.getContextPath()%>/LayUi/queryCar.do' //数据接口
            ,title: '用户表'
            ,page: true //开启分页
            ,toolbar: 'default' //开启工具栏,此处显示默认图标,可以自定义模板,详见文档
            ,totalRow: true //开启合计行
            ,method:"get"
            ,cols: [[ //表头
                {type: 'checkbox', fixed: 'left'}
                ,{field: 'carId', title: 'ID', width:80, sort: true, fixed: 'left', totalRowText: '合计:'}
                ,{field: 'carName', title: '车辆名称', width:80}
                ,{field: 'carPrice', title: '车辆价格', width: 90, sort: true, totalRow: true}
                /*,{field: 'sex', title: '性别', width:80, sort: true}
                ,{field: 'score', title: '评分', width: 80, sort: true, totalRow: true}
                ,{field: 'city', title: '城市', width:150}
                ,{field: 'sign', title: '签名', width: 200}
                ,{field: 'classify', title: '职业', width: 100}
                ,{field: 'wealth', title: '财富', width: 135, sort: true, totalRow: true}*/
                ,{fixed: 'right', width: 165, align:'center', toolbar: '#barDemo'}
            ]]
        });

        //监听头工具栏事件
        table.on('toolbar(test)', function(obj){
            var checkStatus = table.checkStatus(obj.config.id)
                ,data = checkStatus.data; //获取选中的数据
            switch(obj.event){
                case 'add':
                    layer.msg('添加');
                    break;
                case 'update':
                    if(data.length === 0){
                        layer.msg('请选择一行');
                    } else if(data.length > 1){
                        layer.msg('只能同时编辑一个');
                    } else {
                        layer.alert('编辑 [id]:'+ checkStatus.data[0].id);
                    }
                    break;
                case 'delete':
                    if(data.length === 0){
                        layer.msg('请选择一行');
                    } else {
                        layer.msg('删除');
                    }
                    break;
            };
        });

        //监听行工具事件
        table.on('tool(test)', function(obj){ //注:tool 是工具条事件名,test 是 table 原始容器的属性 lay-filter="对应的值"
            var data = obj.data //获得当前行数据
                ,layEvent = obj.event; //获得 lay-event 对应的值
            if(layEvent === 'detail'){
                layer.msg('查看操作');
            } else if(layEvent === 'del'){
                layer.confirm('真的删除行么', function(index){
                    obj.del(); //删除对应行(tr)的DOM结构
                    layer.close(index);
                    //向服务端发送删除指令
                });
            } else if(layEvent === 'edit'){
                layer.msg('编辑操作');
            }
        });

        //执行一个轮播实例
        carousel.render({
            elem: '#test1'
            ,width: '100%' //设置容器宽度
            ,height: 200
            ,arrow: 'none' //不显示箭头
            ,anim: 'fade' //切换动画方式
        });

        //将日期直接嵌套在指定容器中
        var dateIns = laydate.render({
            elem: '#laydateDemo'
            ,position: 'static'
            ,calendar: true //是否开启公历重要节日
            ,mark: { //标记重要日子
                '0-10-14': '生日'
                ,'2018-08-28': '新版'
                ,'2018-10-08': '神秘'
            }
            ,done: function(value, date, endDate){
                if(date.year == 2017 && date.month == 11 && date.date == 30){
                    dateIns.hint('一不小心就月底了呢');
                }
            }
            ,change: function(value, date, endDate){
                layer.msg(value)
            }
        });

        //分页
        laypage.render({
            elem: 'pageDemo' //分页容器的id
            ,count: 100 //总页数
            ,skin: '#1E9FFF' //自定义选中色值
            //,skip: true //开启跳页
            ,jump: function(obj, first){
                if(!first){
                    layer.msg('第'+ obj.curr +'页', {offset: 'b'});
                }
            }
        });

        //上传
        upload.render({
            elem: '#uploadDemo'
            ,url: '' //上传接口
            ,done: function(res){
                console.log(res)
            }
        });

        slider.render({
            elem: '#sliderDemo'
            ,input: true //输入框
        });

        //底部信息
        var footerTpl = lay('#footer')[0].innerHTML;
        lay('#footer').html(layui.laytpl(footerTpl).render({}))
            .removeClass('layui-hide');
    });
</script>
</body>
</html>

效果展示

在这里插入图片描述

  • 7
    点赞
  • 23
    收藏
  • 打赏
    打赏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页
评论 4

打赏作者

Java程序员柚子

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值