关键词

layui的数据表格+springmvc实现搜索功能的例子

下面是详细讲解“layui的数据表格+springmvc实现搜索功能的例子”的完整攻略:

一、前置条件

  1. 确定使用的IDE是IntelliJ IDEA;
  2. 确保已经创建了一个Spring MVC的web工程;
  3. 确保已经配置好了Layui相关的静态资源。

二、添加依赖

添加spring-data-jpa、MySQL JDBC驱动、Spring Web MVC等依赖。

<!-- Spring Web MVC -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>${spring.version}</version>
</dependency>

<!-- Spring Data JPA -->
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-jpa</artifactId>
    <version>${spring-data.version}</version>
</dependency>

<!-- MySQL JDBC Driver -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>${mysql-connector.version}</version>
</dependency>

三、创建数据表格

使用Layui实现一个数据表格,并添加搜索功能。

<table id="userTable" lay-filter="userTable"></table>
<script>
    layui.use('table', function(){
        var table = layui.table;

        table.render({
            elem: '#userTable',
            url: '/user/query',
            cols: [[
              {field:'id', title: 'ID', width:100},
              {field:'username', title: '用户名', width:100},
              {field:'email', title: '邮箱', width:200},
              {field:'phone', title: '手机', width:120},
              {field:'createTime', title: '创建时间', width:200}
            ]],
            page: true,
            limits: [10, 20, 30],
            limit: 10,
            ajaxParams: {
                // ajax参数,可用于搜索等操作
            },
            parseData: function(res){ // res为服务端返回的数据
                return {
                    "code": res.code, // 解析接口状态
                    "msg": res.msg, // 解析提示文本
                    "count": res.data.total, // 解析数据长度
                    "data": res.data.records // 解析数据列表
                };
            }
        });

        // 搜索按钮点击事件
        $('#searchBtn').click(function(){
            var key = $('#searchInput').val();
            table.reload('userTable',{
                where:{
                    'key': key
                }
            });
        });
    });
</script>

四、添加Controller

创建UserController,添加查询用户数据的方法。

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/query")
    @ResponseBody
    public Result query(UserSearchCondition condition) {
        Page<User> page = userService.findByCondition(condition);
        return Result.success(page);
    }
}

// UserSearchCondition.java
@Data
public class UserSearchCondition {

    private Integer page = 1;

    private Integer limit = 10;

    private String key;

    public Pageable getPageable() {
        return PageRequest.of(page - 1, limit);
    }
}

// UserService.java
public interface UserService {

    Page<User> findByCondition(UserSearchCondition condition);
}

// UserServiceImpl.java
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository repository;

    @Override
    public Page<User> findByCondition(UserSearchCondition condition) {
        UserSpecification specification = new UserSpecification(condition);
        return repository.findAll(specification, condition.getPageable());
    }
}

// UserSpecification.java
public class UserSpecification implements Specification<User> {

    private UserSearchCondition condition;

    public UserSpecification(UserSearchCondition condition) {
        this.condition = condition;
    }

    @Override
    public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
        List<Predicate> predicates = new ArrayList<>();
        if (StringUtils.isNotEmpty(condition.getKey())) {
            String pattern = "%" + condition.getKey() + "%";
            Predicate usernameLike = cb.like(root.get("username"), pattern);
            Predicate emailLike = cb.like(root.get("email"), pattern);
            Predicate phoneLike = cb.like(root.get("phone"), pattern);
            predicates.add(cb.or(usernameLike, emailLike, phoneLike));
        }
        return cb.and(predicates.toArray(new Predicate[0]));
    }
}

五、编写SQL脚本

创建user表,并向表中添加一些测试数据。例如:

CREATE TABLE user (
  id int(11) NOT NULL AUTO_INCREMENT,
  username varchar(32) NOT NULL COMMENT '用户名',
  email varchar(64) NOT NULL COMMENT '邮箱',
  phone varchar(16) NOT NULL COMMENT '手机',
  password varchar(64) NOT NULL COMMENT '密码',
  create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户信息表';

INSERT INTO user (id, username, email, phone, password, create_time, update_time)
VALUES
    (1, 'admin', 'admin@qq.com', '13800138000', '123456', '2021-09-15 16:14:12', '2021-09-15 16:14:12'),
    (2, 'tom', 'tom@qq.com', '13900139000', '123456', '2021-09-15 16:14:36', '2021-09-15 16:14:36'),
    (3, 'jack', 'jack@qq.com', '13600136000', '123456', '2021-09-15 16:14:49', '2021-09-15 16:14:49');

六、测试

启动Web应用程序,并在浏览器中访问http://localhost:8080/user/query,将会返回所有用户的数据列表。此时,我们可以在搜索框中输入关键字,点击搜索按钮,即可过滤数据,显示符合搜索条件的数据。

本文链接:http://task.lmcjl.com/news/808.html

展开阅读全文