Springboot后端实现分页功能

一.添加依赖

开发工具 idea ,使用springboot框架,后端使用layui(以后会用Vue,正在学)
后端项目添加依赖web,mysql,mybatis

二.项目大体思路

1.使用注解的方式写sql语句,写了两个sql查询方法,一个获得全部数据(以后用来返回该表中一共有多少数据用,为了传给前端一共多少数据便于分页),另一个就是实现分页功能,怎样设置当前页和每页多少条数据。

三.代码如下

Dao层

package com.example.Dao;

public class User {
    //自增必填不用管
    private Integer id;
    //账号,注册必填
    private String username;
    //密码注册必填
    private String password;

    private String sex;
    //评论,待用
    private String comment;
    private Integer money;
    //房间号,订购房间,待用
    private Integer roomID;

    //真实姓名
    private String name;
    //身份证号
    private String IDcard;
    //手机号
    private String phone;

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", sex='" + sex + '\'' +
                ", comment='" + comment + '\'' +
                ", money=" + money +
                ", roomID=" + roomID +
                ", name='" + name + '\'' +
                ", IDcard='" + IDcard + '\'' +
                ", phone='" + phone + '\'' +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getComment() {
        return comment;
    }

    public void setComment(String comment) {
        this.comment = comment;
    }

    public Integer getMoney() {
        return money;
    }

    public void setMoney(Integer money) {
        this.money = money;
    }

    public Integer getRoomID() {
        return roomID;
    }

    public void setRoomID(Integer roomID) {
        this.roomID = roomID;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getIDcard() {
        return IDcard;
    }

    public void setIDcard(String IDcard) {
        this.IDcard = IDcard;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }
}

Mapper层

package com.example.Mapper;

import com.example.Dao.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserMapper {

    @Select("select * from user")
    List<User> getAll();

    //分页
    @Select("select * from user limit #{start},#{pageSize}")
    public List<User> PageType(@Param("start") int pageNumber,@Param("pageSize") int pageSize);

    @Select("select * from user where username = #{username}")
    User getname(@Param("username")String username);

    @Select("select * from user where username = #{username} AND password = #{password}")
    User getById(@Param("username")String username,@Param("password") String password);

    @Insert("insert into user(username,password) values(#{username},#{password})")
    Integer insert(@Param("username")String username,@Param("password") String password);

    @Delete("delete from user where id = #{id}")
    Integer delete(Integer id);

    @Update("update user set name = #{name},password = #{password},IDcard = #{IDcard},phone = #{phone} where id = #{id}")
    Integer update(User user);


}

Service层

package com.example.Service;

import com.example.Dao.User;

import java.util.List;

public interface UserService {

    User getoneuser(String username);
    User selectUser(String username,String password);
    Boolean insertUser(String username,String password);
    Boolean updateUser(User user);
    Boolean deleteUser(Integer id);
    List<User> getAllUser();
    List<User> queryUser(int pageNumber, int pageSize);



}

实现UserService接口的方法,引入刚刚写的userMapper,把写的方法在UserServiceCase实现,在这里说一下分页的一个公式,因为我的分页是用 Sql 语句的 limit 写的所以分页公式如下
Springboot后端实现分页功能_第1张图片
对应UserServiceCase中的 方法,如下:
Springboot后端实现分页功能_第2张图片
在这里我仅仅使用了在第几页和每页多少数据,因为我的总数据的个数是另外写的。

ServiceCase层

package com.example.Service.imp;

import com.example.Dao.User;
import com.example.Mapper.UserMapper;
import com.example.Service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class UserServiceCase implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User getoneuser(String username) {
        return userMapper.getname(username);
    }

    @Override
    public User selectUser(String username,String password) {
        return userMapper.getById(username,password);
    }

    @Override
    public Boolean insertUser(String username,String password) {
        return userMapper.insert(username,password)>0;
    }

    @Override
    public Boolean updateUser(User user) {
        return userMapper.update(user)>0;
    }

    @Override
    public Boolean deleteUser(Integer id) {
        return userMapper.delete(id)>0;
    }

    @Override
    public List<User> getAllUser() {
        return userMapper.getAll();
    }

    @Override
    public List<User> queryUser(int a, int b) {
        int start=(a-1)*b;

        int pageSize=b;
        return userMapper.PageType(start,pageSize);
    }


}

Controller层:注意,这里我使用HashMap,一个目的是为了保存分页完的列表,另一个是使用list.size()函数来获取该表一共多少数据,把这两个一起传给前端。/getAll接口才是分页的实现和整个数据的获取。

package com.example.Controller;


import com.example.Dao.User;
import com.example.Service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/getAll")
    public Map<String,Object> getAll(int start, int pagesize){
        List<User> userList=userService.getAllUser();

        List<User> userpage=userService.queryUser(start,pagesize);
        Map<String,Object> usermap=new HashMap<>();

        usermap.put("data",userpage);
        usermap.put("total",userList.size());

        System.out.println(usermap);
        return usermap;
    }



    @PostMapping("/insert")
    public Boolean insert(String username,String password){

        System.out.println(userService.insertUser(username,password));
        return userService.insertUser(username,password);
    }

    @PutMapping("/update")
    public Boolean update(User user){

        System.out.println(userService.updateUser(user));
        return userService.updateUser(user);
    }

    @DeleteMapping("/delete")
    public Boolean delete(Integer id){

        System.out.println(userService.deleteUser(id));
        return userService.deleteUser(id);
    }

    @GetMapping("/getById")
    public User getById(String username,String password){

        System.out.println(userService.selectUser(username,password));
        return userService.selectUser(username,password);
    }

    @GetMapping("/getone")
    public User getone(String username){

        System.out.println(userService.getoneuser(username));
        return userService.getoneuser(username);
    }



}

四.前端

html,前端框架我是用的layui,这里是一个分页功能
Springboot后端实现分页功能_第3张图片
js使用axios发请求,getCateList是从数据库获取数据返回给用户查看,renderpage是分页函数的逻辑。在主函数体前有个变量 listParams 目的是设置起始页和后续分页的实现。

$(function () {


    var listParams = {
        start:1,
        pagesize:5
    }


    getCateList()




    function getCateList() {

        axios({

            method: 'GET',
            url: '/users/getAll',
            params:listParams
        }).then(function (res) {

            console.log(res.data)


            var list = []

            res.data.data.forEach(function (item) {
                list.push(`
                <tr>
                    <td>${item.id}</td>
                    <td>${item.username}</td>
                    <td>${item.password}</td>
                    <td>${item.name}</td>
                    <td>${item.IDcard}</td>
                    <td>${item.phone}</td>
                    <td>${item.sex}</td>
                    <td>${item.money}</td>
                    <td> 
                        <button type="button" id="btn-del" class="layui-btn layui-btn-danger layui-btn-sm" data-id="${item.id}">删除 </button>

                    </td>
                </tr> 
                `)
            })

            renderPage(res.data)

            $('tbody').html(list)
        })
    }


    function renderPage(total) {

        layui.laypage.render({

            elem: "pagebox",  //将分页渲染到哪个区域,不需要 #
            count: total.total,          //数据总条数,需要去服务器获取
            limit: listParams.pagesize,  //每页显示条数
            curr: listParams.start,
            layout: ['count', 'limit', 'prev', 'page', 'next', 'skip'],
            limits: [5, 10, 15, 20, 25],

            jump: function (obj, first) {
                //obj包含了当前分页的所有参数,比如:
                console.log(obj.curr) //得到当前页,以便向服务端请求对应页的数据。
                console.log(obj.limit)

                //将当前页码传给pagenum
                listParams.start = obj.curr

                //将每页显示条数赋值给pagesize,可以更改每页显示条数
                listParams.pagesize = obj.limit
                //重新获取文章列表数据
                //需要判断是否为首次加载,如果是,不能重复活的文章列表功能
                if (!first) (
                    getCateList()
                )

            }
        })

    }
})

数据库展示
Springboot后端实现分页功能_第4张图片
前端页面展示
Springboot后端实现分页功能_第5张图片
Springboot后端实现分页功能_第6张图片
Springboot后端实现分页功能_第7张图片

你可能感兴趣的:(spring,boot,java,intellij-idea)