基于SSM和jstl的分页实现


以前用jsp和原生的JDBC实现过分页,现在一看,不仅代码冗余,而且可读性差,今天分享一种简洁的实现方式,我用起来是很方便的。
一.概述
主要思想就是建一个Page类,所有跟分页有关的参数都放在这个类里,这个类里放一个集合用来装返回的数据,前端用JSTL提供的标签进行展示。这里需要注意的是,Oracle与mysql不同,没有提供类似limit这样的函数,稍微麻烦一点,我们用rownum做分页。
我们举个例子,在数据库(Oracle)里有名为Game的一张表,字段有no,name,company,type,现在要做的是在前端用jsp展示,看代码
二.结构
1. model包中有两个类: AnyPage和Game类

public class AnyPage<T> {

    private int currentPage;           //画面接收到的当前页数。
    private int dataCountOnePage = 5;  //每页要显示的数据量。
    private int indexRowNum;           //当前页要显示的第一条记录的行号。
    private int lastRowNum;            //当前页要显示的最后一条记录的行号。
    private int dataCount;             //数据库记录总数
    private int pageCount;             //页码数
    private List<T> games;         //每页要显示的数据集合。
    private T t;

    public T getT() {
        return t;
    }
    public void setT(T t) {
        this.t = t;
    }
    public List<T> getGames() {
        return games;
    }
    public void setGames(List<T> games) {
        this.games = games;
    }
    public int getDataCount() {
        return dataCount;
    }
    //根据数据库总数据量算出总页数
    public void setDataCount(int dataCount) {
        this.dataCount = dataCount;
        pageCount = dataCount / dataCountOnePage;
        if (dataCount % dataCountOnePage != 0) {
            pageCount = pageCount + 1;
        }
    }
    public int getPageCount() {
        return pageCount;
    }
    public void setPageCount(int pageCount) {
        this.pageCount = pageCount;
    }
    public int getCurrentPage() {

        return currentPage;
    }
    //根据当前的页数算出开始和结束的rownum
    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
        this.lastRowNum = currentPage * dataCountOnePage;
        this.indexRowNum = this.lastRowNum - (dataCountOnePage - 1);

    }
    public int getDataCountOnePage() {
        return dataCountOnePage;
    }
    public void setDataCountOnePage(int dataCountOnePage) {
        this.dataCountOnePage = dataCountOnePage;
    }
    public int getIndexRowNum() {
        return indexRowNum;
    }
    public void setIndexRowNum(int indexRowNum) {
        this.indexRowNum = indexRowNum;
    }
    public int getLastRowNum() {
        return lastRowNum;
    }
    public void setLastRowNum(int lastRowNum) {
        this.lastRowNum = lastRowNum;
    }




}

    //Game类
    public class Game {

    //对应数据库的字段
    private int no;
    private String name;
    private String company;
    private String type;


    public int getNo() {
        return no;
    }
    public void setNo(int no) {
        this.no = no;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getCompany() {
        return company;
    }
    public void setCompany(String company) {
        this.company = company;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }



}

在这里AnyPage采用泛型,也是一个小技巧。
2.mapper包:GameMapper的接口和XML配置文件

    //mapper接口
    public interface GameMapper {
    //分页查询
    List<Game> selectByPage(AnyPage anyPage);   
    //统计总数量
    AnyPage selectDataCount();

}

     //XML配置
    <mapper namespace="com.easy.mapper.GameMapper">

    <select id="selectByPage" parameterType="com.easy.model.AnyPage" resultType="com.easy.model.Game">
        select no, name, company, type
        from 
        (select rownum r, no, name, company, type
        from game where no > #{no})
        where r between #{indexRowNum} and #{lastRowNum}
    </select>

    <select id="selectDataCount"  resultType="com.easy.model.AnyPage">
        select count(no) dataCount from game
    </select>


</mapper>

3.service包:GameService接口


    //定义分页查询的接口
    public interface GameService {

    public AnyPage selectByPage(AnyPage anyPage);

}

**4.serviceImpl包**



     //具体实现类,这里用的是spring整合   
     @Service
public class GameServiceImpl implements GameService{
    @Autowired
    GameMapper gameMapper;
    @Override
    public AnyPage selectByPage(AnyPage anyPage) {
    //根据参数查询到分页后的game
        List<Game> list = gameMapper.selectByPage(anyPage);
        //查询总数量
        AnyPage anyPage2 = gameMapper.selectDataCount();
        anyPage2.setGames(list);
        //以AnyPage的形式返回
        return anyPage2;
    }

}

5.Controller包

```
    //这里使用的是SpringMVC作为控制器
    public class GameController {

    @Autowired
    GameService gameService;


    @RequestMapping("sp")
    public String selectByPage(AnyPage anyPage, Map<String, Object> map) {
    //在服务层将分页代码处理好
        AnyPage anyPage2 = gameService.selectByPage(anyPage);
        anyPage2.setCurrentPage(anyPage.getCurrentPage());
        ///以map作为数据模型
        map.put("anyPage", anyPage2);
        return "games";
    }
}

6.前端:jsp

        <h1>分页展示</h1>
    <table border="1" cellspacing="0">
        <tr>
            <td>#</td>
            <td>游戏名</td>
            <td>公司</td>
            <td>类型</td>
        </tr>
        <c:forEach items="${requestScope.anyPage.games}" var="game" varStatus="b1">
            <tr>
                <td>${b1.count}</td>
                <td>${game.name }</td>
                <td>${game.company }</td>
                <td>${game.type }</td>
            </tr>
        </c:forEach>
    </table>


    <c:forEach begin="1" end="${requestScope.anyPage.pageCount }" var="page">
        <c:if test="${not page eq requestScope.anyPage.currentPage }">
            <a href="${pageContext.request.contextPath }/gc/sp?currentPage=${page}">
                ${page}
            </a>
        </c:if>
        <c:if test="${not page eq requestScope.anyPage.currentPage }">
            ${page}
        </c:if>
    </c:forEach>

“`

这里面我截取了其中重要的部分,JSTL提供的标签真的很方便,省去了大量的java代码,可读性性也比较高,还有需要注意的是,最后ye页面编码角标的判断,循环判断的方式也是很好的想法。怎么样,很简单吧。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是使用SSM框架实现分页查询功能的代码实现。以下示例使用PageHelper插件进行分页,Mapper接口使用注解方式配置SQL语句。 1. 在Spring配置文件中配置MyBatis分页插件和数据源等相关信息。 ```xml <!-- MyBatis分页插件配置 --> <bean id="pageHelper" class="com.github.pagehelper.PageHelper"> <property name="properties"> <value> dialect=mysql reasonable=true supportMethodsArguments=true params=count=countSql autoRuntimeDialect=true </value> </property> </bean> <!-- 数据源配置 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/test"/> <property name="username" value="root"/> <property name="password" value="123456"/> </bean> <!-- MyBatis SqlSessionFactory 配置 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="mapperLocations" value="classpath:mapper/*.xml"/> <property name="plugins"> <array> <ref bean="pageHelper"/> </array> </property> </bean> <!-- MyBatis MapperScannerConfigurer 配置 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.example.mapper"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean> ``` 2. 在Mapper接口中定义查询方法,使用MyBatis注解方式配置SQL语句,同时使用PageHelper插件提供的分页参数注解(例如@PageNum、@PageSize)。 ```java public interface UserMapper { /** * 根据条件查询用户列表 * @param name 用户名,模糊查询 * @param pageNum 当前页码 * @param pageSize 每页显示多少条数据 * @return 用户列表 */ @Select("select * from user where name like '%${name}%'") List<User> findUsersByName(@Param("name") String name, @PageNum int pageNum, @PageSize int pageSize); } ``` 3. 在Service层中调用Mapper接口中定义的查询方法,同时传入分页参数。 ```java @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public Page<User> findUsersByName(String name, int pageNum, int pageSize) { PageHelper.startPage(pageNum, pageSize); // 设置分页参数 List<User> userList = userMapper.findUsersByName(name, pageNum, pageSize); // 调用Mapper接口中定义的查询方法 return (Page<User>) userList; } } ``` 4. 在Controller层中获取用户传递的分页参数(例如当前页码、每页显示多少条数据等),并且调用Service层中的方法进行分页查询。 ```java @Controller public class UserController { @Autowired private UserService userService; @GetMapping("/users") public String findUsersByName(Model model, @RequestParam(name = "name", required = false, defaultValue = "") String name, @RequestParam(name = "pageNum", required = false, defaultValue = "1") int pageNum, @RequestParam(name = "pageSize", required = false, defaultValue = "10") int pageSize) { Page<User> userPage = userService.findUsersByName(name, pageNum, pageSize); // 调用Service层中的方法进行分页查询 model.addAttribute("userPage", userPage); return "userList"; } } ``` 5. 在前端页面中展示查询结果,并且展示分页信息(例如总共有多少条数据、当前在第几页、每页显示多少条数据等),同时提供分页导航功能。 ```html <!-- userList.jsp --> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>用户列表</title> </head> <body> <h1>用户列表</h1> <form action="/users" method="get"> <input type="text" name="name" value="${param.name}"/> <input type="submit" value="搜索"/> </form> <table border="1"> <thead> <tr> <th>ID</th> <th>用户名</th> <th>年龄</th> </tr> </thead> <tbody> <c:forEach items="${userPage.list}" var="user"> <tr> <td>${user.id}</td> <td>${user.name}</td> <td>${user.age}</td> </tr> </c:forEach> </tbody> </table> <div> <span>共${userPage.total}条数据</span> <span>当前在第${userPage.pageNum}页</span> <span>每页${userPage.pageSize}条数据</span> <c:if test="${userPage.hasPreviousPage}"> <a href="/users?pageNum=${userPage.prePage}&pageSize=${userPage.pageSize}&name=${param.name}">上一页</a> </c:if> <c:if test="${userPage.hasNextPage}"> <a href="/users?pageNum=${userPage.nextPage}&pageSize=${userPage.pageSize}&name=${param.name}">下一页</a> </c:if> </div> </body> </html> ``` 以上就是使用SSM框架实现分页查询功能的代码实现
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值