JAVA实现分页(前台页面+后台代码)

JAVA分页


前台JSP页面

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>      
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>数据交易猫</title> 
    <script type="text/javascript">   

    //1分页下,动态添加disable给分页按钮
    /*
    $(function(){
        var myPageId="#"+$("#hidCurrentPage").val();
        var myPageAId="#"+$("#hidCurrentPage").val()+" a";
        $(myPageAId).addClass('main-bgcolor');
        $(myPageAId).attr('href','javascript:void(0)')
        $(myPageId).addClass('disabled');
        $(myPageId).addClass('disabledControl');

    })
    */
    //
    $(function(){

    })
    //根据页数查询数据列表
    function queryRequirListByPage(i) {
        var pageNo=i;
        var sortValue=$('#hidSortValue').val();
        $.ajax({
            url:'${pageContext.request.contextPath}/bid/reAction_queryRequirListByPage.action',
            type:'POST',
            data:{
                sortValue:sortValue,
                pageNo:pageNo
            },
            success:function(datas){ 
                $('#requireContentDiv').html(datas);                                       
            },
            error:function(){
                alert("失败");
            },
            });
    }

    //根据下拉查询数据列表
    function selectPage(obj){
        var pageNo=obj.options[obj.selectedIndex].value;
        var sortValue=$('#hidSortValue').val();
        $.ajax({
            url:'${pageContext.request.contextPath}/bid/reAction_queryRequirListByPage.action',
            type:'POST',
            data:{
                sortValue:sortValue,
                pageNo:pageNo
            },
            success:function(datas){ 
                $('#requireContentDiv').html(datas);                                       
            },
            error:function(){
                alert("失败");
            },
            });
        }
    //根据下拉选择排序方式
    function selectSort(obj){
        var sortValue = obj.options[obj.selectedIndex].value;
        var pageNo =1;
        $.ajax({
            url:'${pageContext.request.contextPath}/bid/reAction_queryRequirListByPage.action',
            type:'POST',
            data:{sortValue:sortValue,
                  pageNo:pageNo
                },
            success:function(datas){ 
                $('#requireContentDiv').html(datas);


            },
            error:function(){
                alert("失败");
            },
            });
        }

        $(document).ready(function(){
            var backSortValue=$('#backSortValue').val();
            console.log("backSortValue"+backSortValue)
            $("#category option").each(function(){
                var thisId='#'+this.id;
                var thisValue=this.value;
                if(backSortValue==thisValue){
                    $(thisId).attr('selected','selected');
                }
            });
        })
    </script>   
</head>
<body>

                <!-- 内容-->
                <div  class="well">
                <!-- 标题-->
                    <div class="box"><h3><span class="glyphicon glyphicon-list" ></span>需求列表</h3></div>
                <!-- 筛选条件-->    
                    <div class="box">
                        <div class="row">
                            <div class="col-xs-12">                             
                                  <span>筛选:按</span>
                                    <select id="category" name="category" onchange="selectSort(this)">
                                        <option id="categoryTime" value="publishDatetime">最新</option>
                                        <option id="categoryPrice"  value="price">价格降序</option>
                                        <input id="backSortValue" type="hidden" value="${sortValue}">
                                    </select>
                                    <hr class="mrgZero mrgTopSma"/>
                            </div>
                        </div>
                    </div>                  
                <!-- 内容-->
                        <input type="hidden" name="hidCurrentPage2" id="hidCurrentPage" value="${currentPage}">
                        <input type="hidden" id="hidAllPage" value="${allPage}">
                        <input type="hidden" id="hidSortValue" value="${sortValue}">
                        <s:iterator value="#requiList">

                        <div class="data-down-box">
                            <div class="row">
                                <div class="col-xs-12">
                                    <h4 class="ellipsis"><a href="${pageContext.request.contextPath}/bid/bidAction_queryById?id=${id}" onclick="reward()">${title}</a></h4>
                                </div>                                                                                                  
                            </div>
                            <div class="row mrgTopSma">
                                <div class="col-xs-12 ">                        
                                    <p class="data-provider padLeftBig sec-color ellipsis">悬赏积分:<span>${price}</span></p>
                                    <p class="data-intro padLeftBig ellipsis sec-color">需求描述:<span>${requirementDescription}</span></p>
                                </div>              
                            </div>
                            <hr/>       
                        </div>

                        </s:iterator>
                    <!-- 分页 -->
                    <div id="rePagerDiv" class="rePagerDiv box">
                        <nav>
                          <ul class="pager">

                              <!-- 判断当前页是否位1,如果不为1则显示上一页, -->   
                              <s:if test="1 == #currentPage">     
                              </s:if>
                              <s:else>
                                <li>        
                                  <a href="javascript:void(0)" aria-label="Previous" onclick="queryRequirListByPage(${currentPage-1})">
                                    <span aria-hidden="true">&laquo;</span>
                                  </a>
                                </li>     
                              </s:else>

                            <!-- 首页 -->                              
                            <li><a href="javascript:void(0)" onclick="queryRequirListByPage(1)">首页</a></li>

                            <li>
                                <span><span class="main-color">${currentPage}</span>/&nbsp;${allPage}页</span>                              
                            </li>

                            <!-- 尾页 -->                              
                            <li><a href="javascript:void(0)" onclick="queryRequirListByPage(${allPage})">尾页</a></li>

                            <!-- 判断当前页和总页数,小于则显示下一页, -->    
                            <s:if test="#currentPage < #allPage">
                                <li>
                                  <a href="javascript:void(0)" aria-label="Next" onclick="queryRequirListByPage(${currentPage+1})">
                                    <span aria-hidden="true">&raquo;</span>
                                  </a>
                                </li>
                            </s:if>
                            <li>
                               <span class="skipPageSpan">跳转到第&nbsp;
                                <select onchange="selectPage(this)">
                                    <s:iterator var="lst" begin="1" end="#allPage"  step="1">                                       
                                        <s:if test="%{#lst == #currentPage}">
                                            <option selected="selected" value="<s:property/>" ><s:property/></option>     
                                          </s:if>
                                          <s:else>
                                                <option value="<s:property/>" ><s:property/></option>
                                          </s:else>
                                    </s:iterator>                                                                             
                                </select>
                               &nbsp;页
                               </span>
                             </li>

                          </ul>
                        </nav>

                    </div>                      


                 </div>                     






    <hr/> 

</body>
</html>

action

    //查询需求列表
    public String queryRequirListByPage(){
        int pageSize=5;//每页记录
        String hql="select r from Requirement r where r.reStatus !=2  ";
        if(sortValue == null || sortValue.length() <= 0){
            hql=hql+"order by r.publishDatetime desc";
            ActionContext.getContext().put("sortValue", "publishDatetime"); //当前页码条件
            session.put("sessionReqSortValue","publishDatetime");
        }else{
        hql=hql+"order by r."+sortValue+" desc";
            ActionContext.getContext().put("sortValue", sortValue); //当前页码条件
            session.put("sessionReqSortValue",sortValue);
        }
        long icount=requirementService.countAllRe();//总记录数
        long allPage;//总页数
        //判断是否能整除,能则直接,不能则+1;
        if((icount%pageSize)==0){
            allPage=icount/pageSize;
        }
        else{
            allPage=(icount/pageSize)+1;
        }
        System.out.println("总记录:"+icount+";总页数:"+allPage+";当前页码:"+pageNo);
        List<Requirement> requiList=requirementService.queryByPage(hql, pageNo, pageSize);
        ActionContext.getContext().put("requiList", requiList);//需求列表
        ActionContext.getContext().put("icount", icount);//总记录数
        ActionContext.getContext().put("allPage", allPage);//总页数
        ActionContext.getContext().put("currentPage", pageNo);  //当前页码
        session.put("sessionCurrentPage", pageNo);
        return "requireContent";

    }

service

        public long countAllRe() {
        return requirementDao.countAllRe();
    }
        public List<T> queryByPage(String hql, int pageNo, int pageSize) {
        return requirementDao.queryByPage(hql, pageNo, pageSize);
    }

dao

    //这里可能会报错,就是直接查询数据列表(使用了SSH)
    public long countAll() {
        List<?> l = getSession().createQuery("select count(*) from "
                + clazz.getSimpleName()).list();
        if (l != null && l.size() == 1 )
        {
            return (Long)l.get(0);
        }
        return 0;
    }
    public List<T> queryByPage(String hql, int pageNo, int pageSize) {
        return getSession()
                .createQuery(hql)
                .setFirstResult((pageNo - 1) * pageSize)
                .setMaxResults(pageSize)
                .list();
    }
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
前端 Vue.js 代码: ``` <template> <div> <table> <thead> <tr> <th>ID</th> <th>Name</th> <th>Price</th> </tr> </thead> <tbody> <tr v-for="product in products" :key="product.id"> <td>{{ product.id }}</td> <td>{{ product.name }}</td> <td>{{ product.price }}</td> </tr> </tbody> </table> <el-pagination v-if="total > 0" :page-size="pageSize" :total="total" :current-page="currentPage" @current-change="handlePageChange" /> </div> </template> <script> import axios from 'axios' export default { data() { return { products: [], currentPage: 1, pageSize: 10, total: 0 } }, mounted() { this.getProducts() }, methods: { getProducts() { axios.get('/api/products', { params: { page: this.currentPage, pageSize: this.pageSize } }).then(res => { this.products = res.data.list this.total = res.data.total }) }, handlePageChange(page) { this.currentPage = page this.getProducts() } } } </script> ``` 后端 Java Spring Boot 代码: ``` @RestController @RequestMapping("/api") public class ProductController { @Autowired private ProductService productService; @GetMapping("/products") public PageResult<Product> getProducts(@RequestParam Integer page, @RequestParam Integer pageSize) { return productService.getProducts(page, pageSize); } } ``` ``` @Service public class ProductServiceImpl implements ProductService { @Autowired private ProductRepository productRepository; @Override public PageResult<Product> getProducts(Integer page, Integer pageSize) { Sort sort = Sort.by(Sort.Direction.DESC, "id"); Pageable pageable = PageRequest.of(page - 1, pageSize, sort); Page<Product> productPage = productRepository.findAll(pageable); List<Product> productList = productPage.getContent(); long total = productPage.getTotalElements(); return new PageResult<>(productList, total); } } ``` ``` public interface ProductService { PageResult<Product> getProducts(Integer page, Integer pageSize); } ``` ``` public interface ProductRepository extends JpaRepository<Product, Long> { } ``` 以上是一个简单的Vue.js + Java Spring Boot实现分页功能的示例,具体实现还需要根据业务需求进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值