• LayUI之增加和查询


    前两期的文章里,都使用了LayUI搭建了界面并制作了一些功能:

    LayUI之动态树_小阿飞_的博客-CSDN博客

    使用Layui制作界面及功能_小阿飞_的博客-CSDN博客

    本期精彩:也使用LayUI搭建主界面和增加界面,结合之前封装好了的MVC的jar包,在界面中实现数据库中数据的遍历查询和增加功能

    先一起来看看最终效果叭O(∩_∩)O

    1、数据库建表语句

    1. CREATE TABLE t_book (
    2. id INT(11) NOT NULL AUTO_INCREMENT COMMENT '书本编号',
    3. bookname VARCHAR(20) NOT NULL COMMENT '书本名称',
    4. price FLOAT DEFAULT '0' COMMENT '书本价格',
    5. booktype VARCHAR(20) NOT NULL COMMENT '书本类型',
    6. PRIMARY KEY (`id`)
    7. ) COMMENT='书本信息表';

    项目使用到的jar包👇

     

    2、后台具体代码实现 

    Book实体类

    注:由于我使用了MVC封装的代码,所以Book实体类中的属性要和数据库中的字段名一致

    1. @Table("t_book")
    2. public class Book {
    3. @Key
    4. @AutoIncrement
    5. private Integer id;
    6. private String bookname;
    7. private BigDecimal price;
    8. private String booktype;
    9. public Integer getId() {
    10. return id;
    11. }
    12. public void setId(Integer id) {
    13. this.id = id;
    14. }
    15. public String getBookname() {
    16. return bookname;
    17. }
    18. public void setBookname(String bookname) {
    19. this.bookname = bookname;
    20. }
    21. public BigDecimal getPrice() {
    22. return price;
    23. }
    24. public void setPrice(BigDecimal price) {
    25. this.price = price;
    26. }
    27. public String getBooktype() {
    28. return booktype;
    29. }
    30. public void setBooktype(String booktype) {
    31. this.booktype = booktype;
    32. }
    33. @Override
    34. public String toString() {
    35. return "Book [id=" + id + ", bookname=" + bookname + ", price=" + price + ", booktype=" + booktype + "]";
    36. }
    37. }

    Dao层代码 

    IBookDao接口👇

    1. public interface IBookDao {
    2. List listBooks(String bookname, PageBean pageBean);
    3. /**
    4. * 增加书本信息
    5. * @param book 传入的参数
    6. * @see com.zking.layuit278.model.Book
    7. */
    8. void addBook(Book book);
    9. }

     BookDao实现类👇

    1. public class BookDao implements IBookDao {
    2. @Override
    3. public List listBooks(String bookname, PageBean pageBean) {
    4. String sql = "select * from t_book ";
    5. List param = new ArrayList<>();
    6. if(bookname != null && !"".equals(bookname)) {
    7. sql += "where bookname like ?";
    8. param.add(bookname+"%");
    9. }
    10. return DbTemplate.query(sql, param.toArray(), pageBean, Book.class);
    11. }
    12. @Override
    13. public void addBook(Book book) {
    14. /*String sql = "insert into t_book(bookname, price, booktype) values(?,?,?)";
    15. DbTemplate.update(sql, new Object[] {book.getBookname(),book.getPrice(),book.getBooktype()});*/
    16. DbTemplate.save(book);
    17. }
    18. public static void main(String[] args) {
    19. BookDao dao = new BookDao();
    20. List list = dao.listBooks("红",null);
    21. list.forEach(t -> System.out.println(t));
    22. }
    23. }
    24. Service层

      IBookService接口👇

      1. public interface IBookService {
      2. List listBooks(String bookname, PageBean pageBean);
      3. void addBook(Book book);
      4. }

       BookService接口实现类👇

      1. public class BookService implements IBookService {
      2. private IBookDao dao = new BookDao();
      3. @Override
      4. public List listBooks(String bookname, PageBean pageBean) {
      5. return dao.listBooks(bookname, pageBean);
      6. }
      7. @Override
      8. public void addBook(Book book) {
      9. dao.addBook(book);
      10. }
      11. }

       BookAction类代码👇

      1. public class BookAction extends AbstractDispatchAction implements ModelDrive {
      2. private Book book = new Book();
      3. @Override
      4. public Object getModel() {
      5. return book;
      6. }
      7. private IBookService service = new BookService();
      8. public void listBooks(HttpServletRequest req, HttpServletResponse resp) {
      9. PageBean pageBean = new PageBean();
      10. pageBean.setRequest(req);
      11. try {
      12. List books = service.listBooks(book.getBookname(), pageBean);
      13. CommonUtils.toJson(0, pageBean.getTotal(), books, resp);
      14. } catch (Exception e) {
      15. e.printStackTrace();
      16. CommonUtils.toJson(-1, "操作失败", resp);
      17. }
      18. }
      19. public void addBook(HttpServletRequest req, HttpServletResponse resp) {
      20. try {
      21. service.addBook(book);
      22. CommonUtils.toJson(0, "操作成功", resp);
      23. } catch (Exception e) {
      24. e.printStackTrace();
      25. CommonUtils.toJson(-1, "操作失败", resp);
      26. }
      27. }
      28. }

       3、JSP页面具体代码实现

       主界面👇

      1. <%@ page language="java" contentType="text/html; charset=UTF-8"
      2. pageEncoding="UTF-8"%>
      3. html>
      4. <html>
      5. <head>
      6. <meta charset="utf-8">
      7. <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
      8. <title>layout 后台大布局 - Layuititle>
      9. <%@ include file="common/head.jsp" %>
      10. <style>
      11. #homePage i {
      12. display: none;
      13. }
      14. style>
      15. <script>
      16. let element, $;
      17. layui.use(['jquery','element'], function(){
      18. $ = layui.jquery;
      19. element = layui.element;
      20. $.ajax({
      21. url: ctx+"/loginAction.action?methodName=getModules",
      22. type: 'get',
      23. dataType: 'json',
      24. success: function(resp) {
      25. console.log(resp);
      26. if(resp.code == 1) {
      27. $.each(resp.data, function(index, node) {
      28. //layui-nav-itemed
      29. let opened = index == 0 ? 'layui-nav-itemed' : '';
      30. let li = $('
      31. '">
      32. ');
      33. li.append('' + node.name + '');
      34. let dl = $('
        '
        );
      35. $.each(node.children, function(i,n) {
      36. })
      37. li.append(dl);
      38. $("#menu").append(li);
      39. });
      40. element.render('menu');
      41. }
      42. }
      43. })
      44. });
      45. function openFuncTab(name, id,url) {
      46. let exits = $("#funcTabs li[lay-id="+id+"]").length;
      47. //alert(exits);
      48. if(exits == 0) {
      49. element.tabAdd('funcTabs', {
      50. title: name, //用于演示
      51. content: '',
      52. id: id //实际使用一般是规定好的id,这里以时间戳模拟下
      53. });
      54. }
      55. element.tabChange('funcTabs', id);
      56. setIframeHeight();
      57. $(window).resize(function() {
      58. setIframeHeight();
      59. });
      60. }
      61. function setIframeHeight() {
      62. let h = $(".layui-body").height();
      63. $(".myiframe").css("height", (h-70)+'px');
      64. }
      65. script>
      66. head>
      67. <body class="layui-layout-body">
      68. <div class="layui-layout layui-layout-admin">
      69. <div class="layui-header">
      70. <div class="layui-logo">layui 后台布局div>
      71. <ul class="layui-nav layui-layout-right">
      72. <li class="layui-nav-item">
      73. <a href="javascript:;">
      74. <img src="http://t.cn/RCzsdCq" class="layui-nav-img">
      75. 贤心
      76. a>
      77. <dl class="layui-nav-child">
      78. <dd><a href="">基本资料a>dd>
      79. <dd><a href="">安全设置a>dd>
      80. dl>
      81. li>
      82. <li class="layui-nav-item"><a href="">退了a>li>
      83. ul>
      84. div>
      85. <div class="layui-side layui-bg-black">
      86. <div class="layui-side-scroll">
      87. <ul class="layui-nav layui-nav-tree" id="menu" lay-filter="test">
      88. ul>
      89. div>
      90. div>
      91. <div class="layui-body">
      92. <div style="padding-left: 15px; padding-top: 5px;">
      93. <div class="layui-tab" lay-filter="funcTabs" id="funcTabs" lay-allowclose="true">
      94. <ul class="layui-tab-title">
      95. <li class="layui-this" id="homePage" lay-id="11">首页li>
      96. ul>
      97. <div class="layui-tab-content">
      98. <div class="layui-tab-item layui-show">首页内容div>
      99. div>
      100. div>
      101. div>
      102. div>
      103. <div class="layui-footer">
      104. © layui.com - 底部固定区域
      105. div>
      106. div>
      107. body>
      108. html>
      1. <%@ page language="java" contentType="text/html; charset=UTF-8"
      2. pageEncoding="UTF-8"%>
      3. html>
      4. <html>
      5. <head>
      6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      7. <%@include file="/common/head.jsp" %>
      8. <title>Insert title heretitle>
      9. <script>
      10. let table,$;
      11. layui.use(['table'], function(){
      12. table = layui.table;
      13. $ = layui.$;
      14. $("#btn-qry-book").click(function() {
      15. loadBooks();
      16. })
      17. loadBooks();
      18. $("#btn_add").click(function() {
      19. layer.open({
      20. type: 2, //layer提供了5种层类型。可传入的值有:0(信息框,默认)1(页面层)2(iframe层)3(加载层)4(tips层)
      21. title:'增加书本信息',
      22. area: ['660px', '350px'], //宽高
      23. skin: 'layui-layer-rim', //样式类名
      24. content: ctx+'/jsp/book/addBook.jsp' //书本编辑页面
      25. });
      26. });
      27. });
      28. function loadBooks() {
      29. table.render({
      30. elem: '#test',
      31. url: ctx + '/bookAction.action?methodName=listBooks',
      32. cols: [[
      33. {field:'id', width:80, title: 'ID', sort: true}
      34. ,{field:'bookname', width:180, title: '书名'}
      35. ,{field:'price', width:80, title: '价格', sort: true}
      36. ,{field:'booktype', width:100, title: '类型'}
      37. ]],
      38. page: true,
      39. method: 'post',
      40. where: {
      41. bookname: $("#bookname").val()
      42. },
      43. request: {
      44. pageName: 'page',
      45. limitName: 'rows'
      46. },
      47. loading: true
      48. });
      49. }
      50. script>
      51. head>
      52. <body>
      53. <div class="layui-form-item">
      54. <div class="layui-inline">
      55. <label class="layui-form-label">书名label>
      56. <div class="layui-input-inline">
      57. <input type="tel" id="bookname" name="bookname"
      58. lay-verify="required|phone" autocomplete="off"
      59. class="layui-input">
      60. div>
      61. div>
      62. <div class="layui-inline">
      63. <button class="layui-btn" id="btn-qry-book" lay-submit="" lay-filter="demo1">查询button>
      64. <button id="btn_add" type="button" class="layui-btn"><i class="layui-icon layui-icon-add-1">i> 新增button>
      65. div>
      66. div>
      67. <table class="layui-hide" id="test">table>
      68. body>
      69. html>

       增加界面👇

      1. <%@ page language="java" contentType="text/html; charset=UTF-8"
      2. pageEncoding="UTF-8"%>
      3. html>
      4. <html>
      5. <head>
      6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      7. <%@include file="/common/head.jsp" %>
      8. <title>Insert title heretitle>
      9. <script type="text/javascript">
      10. let form, $;
      11. layui.use(['form'], function(){
      12. form = layui.form;
      13. $ = layui.$;
      14. //监听提交
      15. form.on('submit(book)', function(data){
      16. $.ajax({
      17. url: ctx + '/bookAction.action?methodName=addBook',
      18. data: data.field,
      19. type: 'post',
      20. dataType: 'JSON',
      21. success: function(resp) {
      22. if(resp.code == 0) {
      23. layer.alert('添加成功', {icon: 1}, function() {
      24. var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
      25. parent.layer.close(index);
      26. parent.loadBooks();
      27. });
      28. } else {
      29. layer.alert('添加不成功', {icon: 5});
      30. }
      31. }
      32. })
      33. return false;
      34. });
      35. });
      36. script>
      37. head>
      38. <body>
      39. <form id="book" class="layui-form layui-form-pane">
      40. <div class="layui-form-item">
      41. <label class="layui-form-label">书本名称label>
      42. <div class="layui-input-block">
      43. <input type="text" name="bookname" lay-verify="required" autocomplete="off" placeholder="请输入书本名称" class="layui-input">
      44. div>
      45. div>
      46. <div class="layui-form-item">
      47. <label class="layui-form-label">书本类型label>
      48. <div class="layui-input-block">
      49. <input type="text" name="booktype" lay-verify="required" autocomplete="off" placeholder="请输入书本类型" class="layui-input">
      50. div>
      51. div>
      52. <div class="layui-form-item">
      53. <label class="layui-form-label">书本价格label>
      54. <div class="layui-input-block">
      55. <input type="text" name="price" lay-verify="required|number" autocomplete="off" placeholder="请输入书本价格" class="layui-input">
      56. div>
      57. div>
      58. <div class="layui-form-item" style="text-align:center;">
      59. <button type="button" lay-submit="" lay-filter="book" class="layui-btn layui-btn-normal">保存button>
      60. <button type="reset" class="layui-btn">重置button>
      61. div>
      62. form>
      63. body>
      64. html>
    25. 相关阅读:
      el7升级Apache模块编译
      制造业企业如何高效进行生产计划排单?
      MySQL怎么加锁的?
      Meta Learning 元学习
      优思学院|八大浪费深度剖析
      R语言使用mean函数计算样本(观测)数据中指定变量的相对频数:计算dataframe中指定数据列偏离平均值超过两个标准差的观测样本所占总体的比例
      OpenShift 介绍
      解决java与python整合过程的问题-执行python问题报错
      Idea 编译SpringBoot项目Kotlin报错/Idea重新编译
      lkx语言的总体设计已经发布到github上 (https://github.com/lichuan/lkx)
    26. 原文地址:https://blog.csdn.net/yifei_345678/article/details/126014974