search
HomeJavajavaTutorialDetailed introduction to the front-end page and background code of Java implementation of paging

This article mainly introduces the front-end page and back-end code of Java to realize paging in detail. It has certain reference value. Interested friends can refer to it.

The examples in this article share Java with everyone. The specific code displayed in pagination is for your reference. The specific content is as follows

Let’s look at the picture first, which will give you an idea (ps: SSH framework is used)

Detailed introduction to the front-end page and background code of Java implementation of paging

front deskJSPpage

<%@ 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(&#39;main-bgcolor&#39;);
  $(myPageAId).attr(&#39;href&#39;,&#39;javascript:void(0)&#39;)
  $(myPageId).addClass(&#39;disabled&#39;);
  $(myPageId).addClass(&#39;disabledControl&#39;);

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

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

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


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

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

    <!-- 内容-->
    <p class="well">
    <!-- 标题-->
     <p class="box"><h3 id="span-nbsp-class-glyphicon-nbsp-glyphicon-list-nbsp-span-需求列表"><span class="glyphicon glyphicon-list" ></span>需求列表</h3></p>
    <!-- 筛选条件--> 
     <p class="box">
      <p class="row">
       <p 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"/>
       </p>
      </p>
     </p>     
    <!-- 内容-->
      <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">

      <p class="data-down-box">
       <p class="row">
        <p class="col-xs-12">
         <h4 class="ellipsis"><a href="${pageContext.request.contextPath}/bid/bidAction_queryById?id=${id}" 
         rel="external nofollow" onclick="reward()">${title}</a></h4>
        </p>                         
       </p>
       <p class="row mrgTopSma">
        <p 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>
        </p>    
       </p>
       <hr/>  
      </p>

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

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

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

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

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

       <!-- 判断当前页和总页数,小于则显示下一页, --> 
       <s:if test="#currentPage < #allPage">
        <li>
         <a href="javascript:void(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" 
         rel="external nofollow" aria-label="Next" onclick="queryRequirListByPage(${currentPage+1})">
         <span aria-hidden="true">»</span>
         </a>
        </li>
       </s:if>
       <li>
        <span class="skipPageSpan">跳转到第 
        <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>
         页
        </span>
        </li>

       </ul>
      </nav>

     </p>      


     </p>     

 <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();
 }

The above is the detailed content of Detailed introduction to the front-end page and background code of Java implementation of paging. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JVM performance vs other languagesJVM performance vs other languagesMay 14, 2025 am 12:16 AM

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

Java Platform Independence: Examples of useJava Platform Independence: Examples of useMay 14, 2025 am 12:14 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

JVM Architecture: A Deep Dive into the Java Virtual MachineJVM Architecture: A Deep Dive into the Java Virtual MachineMay 14, 2025 am 12:12 AM

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVM: Is JVM related to the OS?JVM: Is JVM related to the OS?May 14, 2025 am 12:11 AM

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceJava: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceMay 14, 2025 am 12:05 AM

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment