后端学习 | JavaWeb实现简单的分页功能

后端学习 | JavaWeb实现简单的分页功能,第1张

后端学习 | JavaWeb实现简单的分页功能

文章目录

一、创建分页对象

1.1 PageDTO1.2 PageVO 二、创建测试对象

2.1 user表2.2 User实体类2.3 UserDTO2.4 UserVO 三、测试

3.1 业务层3.2 控制器(Servlet)3.3 测试数据和结果


参考博文:一个基础的SpringBoot项目该包含哪些

一、创建分页对象 1.1 PageDTO
public class PageDTO> {

    
    private Integer currPage;
    
    private Integer pageSize;
    
    private String pageDataKey;

    public PageDTO() {
    }

    public PageDTO(Integer currPage, Integer pageSize, String pageDataKey) {
        this.currPage = currPage;
        this.pageSize = pageSize;
        this.pageDataKey = pageDataKey;
    }

    public PageDTO(Integer currPage, Integer pageSize) {
        this.currPage = currPage;
        this.pageSize = pageSize;
    }

    
    @SuppressWarnings("unchecked")
    public T calcCurrPage() {
        // 起始页码 = (当前页码 - 1) * 每页数据数量
        currPage = (currPage - 1) * pageSize;
        // 直接返回泛型对应的对象
        return (T) this;
    }

    public Integer getCurrPage() {
        return currPage;
    }

    public void setCurrPage(Integer currPage) {
        this.currPage = currPage;
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public String getPageDataKey() {
        return pageDataKey;
    }

    public void setPageDataKey(String pageDataKey) {
        this.pageDataKey = pageDataKey;
    }

    @Override
    public String toString() {
        return "PageDTO{" +
                "currPage=" + currPage +
                ", pageSize=" + pageSize +
                ", pageDataKey='" + pageDataKey + ''' +
                '}';
    }
}
1.2 PageVO
@JsonInclude(JsonInclude.Include.NON_NULL)
public class PageVO {

    
    private Integer currPage;

    
    private Integer pageSize;

    
    private Integer totalPage;

    
    private Integer totalCount;

    
    private List pageDataList;

    public PageVO() {
    }

    
    public PageVO setCurrAndSize(PageDTO pageDTO) {

        // 将dto中当前页码和每页数量设置为vo对对应成员变量,也可以使用BeanUtils实现
        this.setCurrPage(pageDTO.getCurrPage());
        this.setPageSize(pageDTO.getPageSize());
        return this;
    }

    
    public void setTotalPageAndCount(Integer totalCount) {
        // 计算总页码
        int totalPage = totalCount / pageSize + (totalCount % pageSize == 0 ? 0 : 1);

        // 设置总页码和总记录数
        this.setTotalCount(totalCount);
        this.setTotalPage(totalPage);
    }

    public Integer getCurPage() {
        return currPage;
    }

    public void setCurrPage(Integer currPage) {
        this.currPage = currPage;
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public Integer getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(Integer totalPage) {
        this.totalPage = totalPage;
    }

    public Integer getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(Integer totalCount) {
        this.totalCount = totalCount;
    }

    public List getPageDataList() {
        return pageDataList;
    }

    public void setPageDataList(List pageDataList) {
        this.pageDataList = pageDataList;
    }

    @Override
    public String toString() {
        return "PageVO{" +
                "curPage=" + currPage +
                ", pageSize=" + pageSize +
                ", totalPage=" + totalPage +
                ", totalCount=" + totalCount +
                ", pageDataList=" + pageDataList +
                '}';
    }
}
二、创建测试对象 2.1 user表
DROp TABLE IF EXISTS `user`;
CREATE TABLE `user` (
	`user_id` INT UNSIGNED NOT NULL UNIQUE AUTO_INCREMENT COMMENT '用户编号-主键',
	`user_name` VARCHAR(20) NOT NULL COMMENT '用户名',
	`gender` TINYINT UNSIGNED DEFAULT 1 COMMENT '性别,1-男;0-女',
	`phone` VARCHAR(12) NOT NULL UNIQUE COMMENT '手机号',
	PRIMARY KEY(`user_id`)
)ENGINE = INNODB DEFAULT CHARSET = utf8 AUTO_INCREMENT = 101 COMMENT '用户表';


INSERT INTO `user`(`user_name`, `gender`, `phone`)
VALUES('张三', 1, '12345678901'),
	('李四', 0, '14345678901'),
	('王五', 1, '15345678901'),
	('赵六', 0, '17345678901');
2.2 User实体类
public class User {

    private Integer userId;
    private String userName;
    private Integer gender;
    private String phone;

    public User() {
    }

    public User(Integer userId, String userName, Integer gender, String phone) {
        this.userId = userId;
        this.userName = userName;
        this.gender = gender;
        this.phone = phone;
    }

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Integer getGender() {
        return gender;
    }

    public void setGender(Integer gender) {
        this.gender = gender;
    }

    public String getPhone() {
        return phone;
    }

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

    @Override
    public String toString() {
        return "User{" +
                "userId=" + userId +
                ", userName='" + userName + ''' +
                ", gender=" + gender +
                ", phone='" + phone + ''' +
                '}';
    }
}
2.3 UserDTO
public class UserDTO extends PageDTO {

    private Integer userId;
    private String phone;

    public UserDTO() {
    }

    public UserDTO(Integer userId, String phone) {
        this.userId = userId;
        this.phone = phone;
    }

    public UserDTO(Integer currPage, Integer pageSize, String pageDataKey, Integer userId, String phone) {
        super(currPage, pageSize, pageDataKey);
        this.userId = userId;
        this.phone = phone;
    }

    public UserDTO(Integer currPage, Integer pageSize, Integer userId, String phone) {
        super(currPage, pageSize);
        this.userId = userId;
        this.phone = phone;
    }

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getPhone() {
        return phone;
    }

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

    @Override
    public String toString() {
        return "UserDTO{" +
                "userId=" + userId +
                ", phone='" + phone + ''' +
                '}';
    }
}
2.4 UserVO
public class UserVO {

    private Integer userId;
    private String userName;
    private String gender;
    private String phone;

    public UserVO() {
    }

    public UserVO(Integer userId, String userName, String gender, String phone) {
        this.userId = userId;
        this.userName = userName;
        this.gender = gender;
        this.phone = phone;
    }

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getPhone() {
        return phone;
    }

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

    @Override
    public String toString() {
        return "UserVO{" +
                "userId=" + userId +
                ", userName='" + userName + ''' +
                ", gender='" + gender + ''' +
                ", phone='" + phone + ''' +
                '}';
    }
}
三、测试

PS:持久层略

3.1 业务层
public class UserServiceImpl implements UserService {

    private final UserDao userDao = new UserDaoImpl();

    
    @Override
    public PageVO listPageUsersInfo(UserDTO userDTO) {
        // 创建一个分页VO,同时设置当前页码和每页数量
        PageVO pageVO = new PageVO().setCurrAndSize(userDTO);

        // 更新当前页码,方便数据库查询
        userDTO = userDTO.calcCurrPage();

        // 查询分页数据
        List users = userDao.listPageUsers(userDTO.getCurrPage(), userDTO.getPageSize());

        // 判断是否获取成功
        if (null == users) {
            return null;
        }

        // 存储vo集合
        List userVOList = new ArrayList<>();

        // 将实体集合转成VO集合
        for (User u : users) {
            UserVO userVO = new UserVO();

            // 也可以使用BeanUtils工具类
            userVO.setUserId(u.getUserId());
            userVO.setUserName(u.getUserName());
            userVO.setGender(u.getGender() == 1 ? "男" : "女");
            userVO.setPhone(u.getPhone());

            // 存入集合
            userVOList.add(userVO);
        }

        // 设置分页数据
        pageVO.setPageDataList(userVOList);

        // 查询总记录数
        int totalCount = userDao.countAll();
        // 设置总记录数和总页码
        pageVO.setTotalPageAndCount(totalCount);

        return pageVO;
    }
}
3.2 控制器(Servlet)
@WebServlet("/user/pageUsers")
public class UserServlet extends HttpServlet {

    private final UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        // 设置请求编码方式
        req.setCharacterEncoding("utf-8");
        // 设置响应数据格式和编码方式
        resp.setContentType("application/json;charset=utf-8");

        // 根据请求对象request中请求体转成对象
        UserDTO userDTO = JsonUtils.getObjectFromReqBody(req, UserDTO.class);

        // 调用service方法,获取分页对象
        PageVO pageVO = userService.listPageUsersInfo(userDTO);

        // 创建响应对象
        ResultInfo> resultInfo =
                new ResultInfo<>(200, "请求成功", pageVO);

        // 将对象转成json字符串
        String resJson = JsonUtils.getJsonFromObject(resultInfo);

        // 判断是否转化成功
        if (null != resJson) {
            // 响应数据
            resp.getWriter().write(resJson);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
3.3 测试数据和结果

测试数据

PS: 这里的用户id和手机号没用到,就随便写了

测试结果/响应结果

测试源码地址

github:https://github.com/keyhuy/paging-test码云:https://gitee.com/keyhuy/paging-test

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5712961.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-18
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存