Jfianl+layui实现基本增删改查

实现效果

image.png

用idea创建maven项目 目录结构如下

image.png

在src/main文件下创建webapp目录,用来存放页面、js、css等文件。assets文件用来存放js、css,view用来存放页面视图,

image.png

引入依赖

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.demo</groupId>
    <artifactId>jfinal-demo2</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>com.jfinal</groupId>
            <artifactId>jfinal</artifactId>
            <version>4.3</version>
        </dependency>
        <dependency>
            <groupId>com.jfinal</groupId>
            <artifactId>jfinal-undertow</artifactId>
            <version>1.7</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.44</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.9</version>
        </dependency>
    </dependencies>
</project>

在rescourse下创建properties文件数据库信息

jdbcUrl = jdbc:mysql://localhost:3306/jfinal_demo?characterEncoding=utf8&useSSL=false
user = root
password =

在WEB-INF下创建web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>jfinal-demo</display-name>
  <filter>
    <filter-name>jfinal</filter-name>
    <filter-class>com.jfinal.core.JFinalFilter</filter-class>  //是jfinal 封装好的一个过滤器,
    <init-param>
      <param-name>configClass</param-name>
      <param-value>com.demo.config.BaseConfig</param-value>   //BaseConfig文件在项目中的位置
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>jfinal</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

创建Config文件

public class BaseConfig extends JFinalConfig {
    /**
     * 启动入口,运行此 main 方法可以启动项目,此 main 方法可以放置在任意的 Class 类定义中,不一定要放于此
     */
    public static void main(String[] args) {
        UndertowServer.start(BaseConfig.class);
    }

    /**
     * 配置JFinal常量值
     * @param me
     */
    public void configConstant(Constants me) {
        me.setReportAfterInvocation(false);//设置 devMode 之下的 action report 是否在 invocation 之后,默认值为 true
        PropKit.use("jdbc.properties");//读取配置文件
        me.setDevMode(true);//设置开发模式
    }

    /**
     * 配置访问路由
     * @param me
     */
    public void configRoute(Routes me) {
       me.add("/", BlogController.class, "/view");
    }

    /**
     * 配置引擎
     * @param me
     */
    public void configEngine(Engine me) {
       //设置共享页面,在页面上通过#define layopen()定义模板,#@layopen()引用
        me.addSharedFunction("/view/common/_layopen.html");
    }

    public void configPlugin(Plugins me) {
        DruidPlugin dp = new DruidPlugin(PropKit.get("jdbcUrl"), PropKit.get("user"), PropKit.get("password"));
        me.add(dp);//配置数据库连接池

        ActiveRecordPlugin arp = new ActiveRecordPlugin(dp);//建立数据库表名到Model的映射关系
        arp.addMapping("blog", "id", Blog.class);
        me.add(arp);
    }

    public void configInterceptor(Interceptors me) {
    }

    public void configHandler(Handlers handlers) {

    }
}

创建Mode,实现增删改查等功能

public class Blog extends Model<Blog> {

    public static final Blog blogDao = new Blog();
}

创建Controller

public class BlogController extends Controller {

    @Before(BlogIntercepter.class)
    public void index(){
        render("list.html");
    }

    public void getList(){
        Integer pageNum = getParaToInt("page");
        Integer pageSize = getParaToInt("limit");
        Page<Blog> blogs = Blog.blogDao.paginate(pageNum,pageSize,"select * ","from blog");
        renderJson(blogs);
    }

    public void form(){
        render("add.html");
    }

    /**
     * 提交方法
     */
    @Before(BlogValidator.class)
    public  void submit(){
        Blog blog = getModel(Blog.class,"blog");
        blog.save();
       renderJson(Ret.ok());
    }
    /**
     * 编辑方法
     */
    public void edit(){
        Integer id = getParaToInt(0);
        if(id!=null&&id>0){
            setAttr("blog",Blog.blogDao.findById(id));
        }
        render("edit.html");
    }
    /**
     * 删除方法
     */
    public void del(){
        Blog.blogDao.deleteById(getPara(0));
        redirect("/");
    }
    /**
     * 更新方法
     */
    public void update(){
        Blog blog = getModel(Blog.class,"blog");
        blog.update();
        redirect("/");
    }
}

在webapp/view/common目录下定义通用模板_layopen.html,存放通用js、css等

#define layopen()
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>测试</title>
    <link rel="stylesheet" type="text/css" href="/assets/layui/css/layui.css">
    #@css?()
</head>
<body  class="layui-layout-body">
#@main()
</body>
<script type="text/javascript" src="/assets/jquery/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="/assets/layui/layui.all.js"></script>
#@js?()

</html>
#end

在webapp/view创建list页面

#define css()
<style>
    .layui-table-cell{
        display:table-cell;
        vertical-align: middle;
    }
</style>
#end
#define main()
<div class="layui-content" style="width: 90%;margin-left: 20px">
    <div class="layui-row" style="margin-top: 20px">
        <button type="button" class="layui-btn layui-btn-normal"><a onclick="add()" style="color: #ffffff">新增用户</a></button>
    </div>
    <table id="demo" lay-filter="test" ></table>
</div>
#end

#define js()
<script type="text/html" id="operate">
    <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit">修改</a>
    <a class="layui-btn layui-btn-normal layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<script>
    var tableIns;
    layui.use('table', function () {
        var table = layui.table,
            form = layui.form;

        //第一个实例
        tableIns = table.render({
            elem: '#demo'
            , url: '/getList' //数据接口
            ,limit: 10
            , page: true //开启分页
            , cols: [[
                {field: 'id', title: 'id',width:100}
                ,{field: 'title', title: '标题',width:100}
                ,{field: 'content', title: '内容',width:100}
                ,{fixed: 'right', title: '操作',align:'center',toolbar:'#operate'}
            ]]
            , parseData: function (res) {
                return {
                    "code": 0,
                    "msg": "",
                    "count": res.totalRow,
                    "data": res.list
                }
            }
        });

        table.on('tool(test)', function (obj) { //注:tool是工具条事件名,test是table原始容器的属性 lay-filter="对应的值"
            var data = obj.data, //获得当前行数据
                layEvent = obj.event; //获得 lay-event 对应的值

            if (layEvent === 'del') {
                    layer.confirm('确定要删除吗', {
                        btn: ['确定', '取消'] 
                    }, function(index, layero){
                        //按钮【按钮一】的回调
                        $.post("/del/"+data.id,function (result) {
                            layer.msg("删除成功", {offset: '300px', shade: [0.8, '#393D49']});
                            layer.close(index)
                            tableIns.reload({
                                page:{
                                    curr:1
                                }
                            })
                        });
                    }, function(index){
                        layer.close(index)
                    });
            } else if (layEvent === 'edit') {
                layer.open({
                    type:2,
                    title:"修改",
                    shade: 0.8,
                    area: ['500px', '300px'],
                    content: "/edit/"+data.id,//请求路径跳转edit页面
                })

            }
        });
    });

    function add(){
        layer.open({
            type:2,  //iframe嵌套
            title:"添加",
            shade: 0.8,
            area: ['500px', '300px'],
            content: "/form",  //请求路径跳转add页面
        })
    }
</script>
#end

add页面

#@layopen()

#define main()
<form id="add" class="layui-form" style="margin-top: 20px">
    <div class="layui-form-item">
        <label class="layui-form-label">标题</label>
        <div class="layui-input-block">
            <input type="text" name="blog.title" placeholder="请输入标题" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">content</label>
        <div class="layui-input-block">
             <input type="text" name="blog.content" placeholder="请输入内容" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="formDemo">立即提交</button>
        </div>
    </div>
</form>
#end

#define js()
<script>
    layui.use('form', function () {
        var table = layui.table,
            form = layui.form;

        form.on('submit(formDemo)', function(data){
            $.ajax({
                url: "/submit",
                data: data.field,
                success: function (data) {
                    layer.msg("添加成功");
                    window.parent.location.reload();
                },
            })
            return false;
        })
    })
</script>
#end

edit页面

#@layopen()
#define main()
<form id="add" class="layui-form" style="margin-top: 20px">
    <input type="hidden" name="blog.id"value="#(blog.id)" autocomplete="off" class="layui-input">
    <div class="layui-form-item">
        <label class="layui-form-label">标题</label>
        <div class="layui-input-block">
            <input type="text" name="blog.title" value="#(blog.title)" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">内容</label>
        <div class="layui-input-block">
            <input type="text" name="blog.content" value="#(blog.content)"  class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="formDemo">立即提交</button>
        </div>
    </div>
</form>
#end
#define js()
<script>
    layui.use('form', function () {
        var table = layui.table,
            form = layui.form;

        form.on('submit(formDemo)', function(data){
            $.ajax({
                url: "/update",
                data: data.field,
                success: function (data) {
                    layer.msg("修改成功");
                    window.parent.location.reload();
                },
            })
            return false;
        })
    })
</script>
#end


评论区

不知所以

2019-07-11 17:14

厉害了。

杜福忠

2019-07-11 17:49

o(∩_∩)o 这个画风一看就是我们北京新加入的小伙伴啊~ 兄弟们给赞一个~

山东小木

2019-07-12 11:39

不错