Spring Data Jpa+SpringMVC+Jquery.pagination.js实现分页示例
程序员文章站
2023-12-22 09:53:58
本博客介绍基于spring data这款orm框架加上 jquery.pagination插件实现的分页功能。
本博客是基于一款正在开发中的github开源项目的,项目代...
本博客介绍基于spring data这款orm框架加上 jquery.pagination插件实现的分页功能。
本博客是基于一款正在开发中的github开源项目的,项目代码地址:
欢迎star(收藏)或者可以下载去学习,还在开发…
介绍一下spring data框架
spring data : spring 的一个子项目。用于简化数据库访问,支持nosql 和 关系数据存储。
下面给出springdata 项目所支持 nosql 存储:
* mongodb (文档数据库)
* neo4j(图形数据库)
* redis(键/值存储)
* hbase(列族数据库)
springdata 项目所支持的关系数据存储技术:
* jdbc
* jpa
jpa spring data : 致力于减少数据访问层 (dao) 的开发量。开发者只要写好持久层接口就好,然后其它的框架会帮程序员实现。
开发步骤:
【spring data实现数据获取】
本项目是采用maven的,所以可以参考一下我的maven配置:
<project xmlns="http://maven.apache.org/pom/4.0.0" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://maven.apache.org/pom/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <parent> <artifactid>muses</artifactid> <groupid>org.muses</groupid> <version>1.0-snapshot</version> </parent> <modelversion>4.0.0</modelversion> <artifactid>jeeplatform-admin</artifactid> <packaging>war</packaging> <name>jeeplatform-admin maven webapp</name> <url>http://maven.apache.org</url> <properties> <spring.version>4.1.5.release</spring.version> <spring-data-jpa.version>1.4.2.release</spring-data-jpa.version> <spring-data-commons.version>1.6.2.release</spring-data-commons.version> <hibernate.version>4.3.8.final</hibernate.version> <shiro.version>1.2.3</shiro.version> <lucene.version>4.7.2</lucene.version> <druid.version>1.0.9</druid.version> <poi.version>3.7</poi.version> </properties> <dependencies> <!-- module start --> <dependency> <groupid>org.muses</groupid> <artifactid>jeeplatform-core</artifactid> <version>${jeeplatform.core.version}</version> </dependency> <dependency> <groupid>org.muses</groupid> <artifactid>jeeplatform-common</artifactid> <version>1.0-snapshot</version> </dependency> <dependency> <groupid>org.muses</groupid> <artifactid>jeeplatform-oss</artifactid> <version>${jeeplatform.oss.version}</version> </dependency> <dependency> <groupid>org.muses</groupid> <artifactid>jeeplatform-upms</artifactid> <version>1.0-snapshot</version> </dependency> <!-- moudle end--> <!-- servlet start--> <dependency> <groupid>javax.servlet</groupid> <artifactid>servlet-api</artifactid> <version>2.5</version> <scope>provided</scope> </dependency> <!-- servlet end --> <!-- jstl start--> <dependency> <groupid>jstl</groupid> <artifactid>jstl</artifactid> <version>1.2</version> </dependency> <dependency> <groupid>taglibs</groupid> <artifactid>standard</artifactid> <version>1.1.2</version> </dependency> <!-- jstl end --> <!-- log4j start--> <dependency> <groupid>log4j</groupid> <artifactid>log4j</artifactid> <version>${log4j.version}</version> </dependency> <!-- log4j end--> <!-- json解析需要的jar start--> <dependency> <groupid>commons-beanutils</groupid> <artifactid>commons-beanutils</artifactid> <version>1.8.3</version> </dependency> <dependency> <groupid>commons-collections</groupid> <artifactid>commons-collections</artifactid> <version>3.2.1</version> </dependency> <dependency> <groupid>net.sf.ezmorph</groupid> <artifactid>ezmorph</artifactid> <version>1.0.6</version> </dependency> <dependency> <groupid>commons-lang</groupid> <artifactid>commons-lang</artifactid> <version>2.5</version> </dependency> <dependency> <groupid>commons-logging</groupid> <artifactid>commons-logging</artifactid> <version>1.2</version> </dependency> <dependency> <groupid>net.sf.json-lib</groupid> <artifactid>json-lib</artifactid> <version>2.4</version> <type>jar</type> <classifier>jdk15</classifier> <scope>compile</scope> </dependency> <!-- json解析需要的jar end --> <!-- mysql start--> <dependency> <groupid>mysql</groupid> <artifactid>mysql-connector-java</artifactid> <version>${mysql.version}</version> </dependency> <!-- mysql end--> <!-- commons --> <dependency> <groupid>commons-io</groupid> <artifactid>commons-io</artifactid> <version>2.0.1</version> </dependency> <dependency> <groupid>commons-fileupload</groupid> <artifactid>commons-fileupload</artifactid> <version>1.2.2</version> </dependency> <!-- commons --> <!-- spring framework start--> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-core</artifactid> <version>${spring.version}</version> </dependency> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-beans</artifactid> <version>${spring.version}</version> </dependency> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-context</artifactid> <version>${spring.version}</version> </dependency> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-context-support</artifactid> <version>${spring.version}</version> </dependency> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-jdbc</artifactid> <version>${spring.version}</version> </dependency> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-tx</artifactid> <version>${spring.version}</version> </dependency> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-test</artifactid> <version>${spring.version}</version> <scope>test</scope> </dependency> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-web</artifactid> <version>${spring.version}</version> </dependency> <!-- spring framework end --> <!-- spring aop start--> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-aop</artifactid> <version>${spring.version}</version> </dependency> <dependency> <groupid>org.aspectj</groupid> <artifactid>aspectjweaver</artifactid> <version>1.6.10</version> </dependency> <!-- spring aop end --> <!-- springmvc start--> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-webmvc</artifactid> <version>${spring.version}</version> </dependency> <!-- springmvc end --> <!-- spring data start--> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-orm</artifactid> <version>${spring.version}</version> </dependency> <dependency> <groupid>org.springframework.data</groupid> <artifactid>spring-data-jpa</artifactid> <version>${spring-data-jpa.version}</version> </dependency> <dependency> <groupid>org.springframework.data</groupid> <artifactid>spring-data-commons</artifactid> <version>${spring-data-commons.version}</version> </dependency> <!-- spring data end --> <!-- hibernate jpa start--> <dependency> <groupid>org.hibernate.javax.persistence</groupid> <artifactid>hibernate-jpa-2.1-api</artifactid> <version>1.0.0.final</version> </dependency> <dependency> <groupid>org.hibernate</groupid> <artifactid>hibernate-core</artifactid> <version>${hibernate.version}</version> </dependency> <dependency> <groupid>org.hibernate</groupid> <artifactid>hibernate-entitymanager</artifactid> <version>${hibernate.version}</version> </dependency> <!-- hibernate jpa end --> <!-- hibernate echache start--> <dependency> <groupid>org.slf4j</groupid> <artifactid>slf4j-api</artifactid> <version>1.6.1</version> </dependency> <dependency> <groupid>net.sf.ehcache</groupid> <artifactid>ehcache-core</artifactid> <version>2.5.0</version> </dependency> <dependency> <groupid>org.hibernate</groupid> <artifactid>hibernate-ehcache</artifactid> <version>${hibernate.version}</version> </dependency> <!-- hibernate echache end --> <!-- 阿里的连接池druid start--> <dependency> <groupid>com.alibaba</groupid> <artifactid>druid</artifactid> <version>${druid.version}</version> </dependency> <!-- 阿里的连接池druid end--> <!--shiro start--> <dependency> <groupid>org.apache.shiro</groupid> <artifactid>shiro-all</artifactid> <version>${shiro.version}</version> </dependency> <!-- shiro end--> <!-- velocity start--> <dependency> <groupid>org.apache.velocity</groupid> <artifactid>velocity</artifactid> <version>1.6</version> </dependency> <dependency> <groupid>org.apache.velocity</groupid> <artifactid>velocity-tools</artifactid> <version>2.0</version> </dependency> <!-- velocity end--> <!-- lucene全文搜素引擎 start--> <dependency> <groupid>org.apache.lucene</groupid> <artifactid>lucene-core</artifactid> <version>${lucene.version}</version> </dependency> <dependency> <groupid>org.apache.lucene</groupid> <artifactid>lucene-analyzers-common</artifactid> <version>${lucene.version}</version> </dependency> <dependency> <groupid>org.apache.lucene</groupid> <artifactid>lucene-queryparser</artifactid> <version>${lucene.version}</version> </dependency> <dependency> <groupid>org.apache.lucene</groupid> <artifactid>lucene-memory</artifactid> <version>${lucene.version}</version> </dependency> <dependency> <groupid>org.apache.lucene</groupid> <artifactid>lucene-highlighter</artifactid> <version>${lucene.version}</version> </dependency> <!-- 注意ikanalyzer没有maven坐标,请自行添加到本地仓库 --> <dependency> <groupid>org.wltea.analyzer</groupid> <artifactid>ikanalyzer</artifactid> <version>2012ff_u1</version> <scope>system</scope> <systempath>${basedir}/src/main/webapp/web-inf/lib/ikanalyzer2012ff_u1.jar</systempath> </dependency> <!-- lucene全文搜素引擎 end --> <!-- log4j start--> <dependency> <groupid>log4j</groupid> <artifactid>log4j</artifactid> <version>${log4j.version}</version> </dependency> <!-- log4j end--> <!-- json解析需要的jar start--> <dependency> <groupid>commons-beanutils</groupid> <artifactid>commons-beanutils</artifactid> <version>1.8.3</version> </dependency> <dependency> <groupid>commons-collections</groupid> <artifactid>commons-collections</artifactid> <version>3.2.1</version> </dependency> <dependency> <groupid>net.sf.ezmorph</groupid> <artifactid>ezmorph</artifactid> <version>1.0.6</version> </dependency> <dependency> <groupid>commons-lang</groupid> <artifactid>commons-lang</artifactid> <version>2.5</version> </dependency> <dependency> <groupid>commons-logging</groupid> <artifactid>commons-logging</artifactid> <version>1.2</version> </dependency> <dependency> <groupid>net.sf.json-lib</groupid> <artifactid>json-lib</artifactid> <version>2.4</version> <type>jar</type> <classifier>jdk15</classifier> <scope>compile</scope> </dependency> <!-- json解析需要的jar end --> <!-- poi start--> <dependency> <groupid>org.apache.poi</groupid> <artifactid>poi</artifactid> <version>${poi.version}</version> </dependency> <!-- poi end--> <!-- email start--> <dependency> <groupid>com.sun.mail</groupid> <artifactid>javax.mail</artifactid> <version>1.5.6</version> </dependency> <!-- email end--> </dependencies> <build> <finalname>jeeplatform-admin</finalname> </build> </project>
设计好数据库,编写一个实体类:
package org.muses.jeeplatform.model.entity; import java.util.date; import java.util.set; import javax.persistence.cascadetype; import javax.persistence.column; import javax.persistence.entity; import javax.persistence.fetchtype; import javax.persistence.generatedvalue; import javax.persistence.generationtype; import javax.persistence.id; import javax.persistence.joincolumn; import javax.persistence.jointable; import javax.persistence.manytomany; import javax.persistence.table; import javax.persistence.temporal; import javax.persistence.temporaltype; /** * 用户信息的实体类 * @author nicky */ @entity @table(name="sys_user") public class user { /** 用户id**/ private int id; /** 用户名**/ private string username; /** 用户密码**/ private string password; /** 手机号**/ private int phone; /** 性别**/ private string sex; /** 邮件**/ private string email; /** 备注**/ private string mark; /** 用户级别**/ private string rank; /** 最后一次时间**/ private date lastlogin; /** 登录ip**/ private string loginip; /** 图片路径**/ private string imageurl; /** 注册时间**/ private date regtime; /** 账号是否被锁定**/ private boolean locked = boolean.false; private set<role> roles; @generatedvalue(strategy=generationtype.identity) @id public int getid() { return id; } public void setid(int id) { this.id = id; } @column(unique=true,length=100,nullable=false) public string getusername() { return username; } public void setusername(string username) { this.username = username; } @column(length=100,nullable=false) public string getpassword() { return password; } public void setpassword(string password) { this.password = password; } public int getphone() { return phone; } public void setphone(int phone) { this.phone = phone; } @column(length=6) public string getsex() { return sex; } public void setsex(string sex) { this.sex = sex; } @column(length=100) public string getemail() { return email; } public void setemail(string email) { this.email = email; } @column(length=30) public string getmark() { return mark; } public void setmark(string mark) { this.mark = mark; } @column(length=10) public string getrank() { return rank; } public void setrank(string rank) { this.rank = rank; } @temporal(temporaltype.date) public date getlastlogin() { return lastlogin; } public void setlastlogin(date lastlogin) { this.lastlogin = lastlogin; } @column(length=100) public string getloginip() { return loginip; } public void setloginip(string loginip) { this.loginip = loginip; } @column(length=100) public string getimageurl() { return imageurl; } public void setimageurl(string imageurl) { this.imageurl = imageurl; } @temporal(temporaltype.date) @column(nullable=false) public date getregtime() { return regtime; } public void setregtime(date regtime) { this.regtime = regtime; } public boolean getlocked() { return locked; } public void setlocked(boolean locked) { this.locked = locked; } }
编写接口实现spring data框架的pagingandsortingrepository接口
package org.muses.jeeplatform.repository; import org.muses.jeeplatform.model.entity.user; import org.springframework.data.domain.page; import org.springframework.data.domain.pageable; import org.springframework.data.jpa.repository.jparepository; import org.springframework.data.jpa.repository.query; import org.springframework.data.repository.pagingandsortingrepository; import org.springframework.data.repository.query.param; import java.util.date; public interface userrepository extends pagingandsortingrepository<user, integer> { /*user findbyusername(string username); @query("from user u where u.username=:username and u.password=:password") user findbyusernameandpassword(@param("username") string username, @param("password") string password); @query("from user u where u.id=:id") user findbyid(@param("id") int id); @query("from user u where date_format(u.lastlogin,'yyyy-mm-dd') between date_format((:startdate),'yyyy-mm-dd') and date_format((:enddate),'yyyy-mm-dd')") page<user> searchu(@param("startdate")date startdate,@param("enddate")date enddate, pageable pageable); */ }
业务类实现:
package org.muses.jeeplatform.service; import java.util.*; import org.muses.jeeplatform.model.entity.user; import org.muses.jeeplatform.repository.userrepository; import org.springframework.beans.factory.annotation.autowired; import org.springframework.data.domain.page; import org.springframework.data.domain.pagerequest; import org.springframework.data.domain.sort; import org.springframework.data.jpa.domain.specification; import org.springframework.stereotype.service; import org.springframework.transaction.annotation.transactional; import javax.persistence.criteria.criteriabuilder; import javax.persistence.criteria.criteriaquery; /** * @description 用户信息管理的业务类 * @author nicky * @date 2017年3月6日 */ @service public class userservice { @autowired userrepository userrepository; /** * 构建pagerequest对象 * @param num * @param size * @param asc * @param string * @return */ private pagerequest buildpagerequest(int num, int size, sort.direction asc, string string) { return new pagerequest(num-1, size,null,string); } /** * 获取所有的菜单信息并分页显示 * @param pageno * 当前页面数 * @param pagesize * 每一页面的页数 * @return */ @transactional public page<user> findall(int pageno, int pagesize, sort.direction dir, string str){ pagerequest request = buildpagerequest(pageno, pagesize, dir, str); page<user> users = userrepository.findall(request); return users; } }
控制类,采用springmvc框架,先编写一个basecontroller,实现一些通用功能的封装:
package org.muses.jeeplatform.web.controller; import javax.servlet.http.httpservletrequest; import org.slf4j.logger; import org.slf4j.loggerfactory; import org.springframework.web.context.request.requestcontextholder; import org.springframework.web.context.request.servletrequestattributes; import org.springframework.web.servlet.modelandview; public class basecontroller { logger log = null; /** * 获取日志对象 * @return */ public logger getinstance(){ if(log == null){ log = loggerfactory.getlogger(basecontroller.class); } return log; } /** * 得到request对象 */ public httpservletrequest getrequest() { httpservletrequest request = ((servletrequestattributes)requestcontextholder.getrequestattributes()).getrequest(); return request; } /** * 得到modelandview */ public modelandview getmodelandview(){ return new modelandview(); } }
控制类实现:
package org.muses.jeeplatform.web.controller; import net.sf.json.jsonarray; import net.sf.json.jsonobject; import net.sf.json.jsonconfig; import org.apache.commons.collections.map.hashedmap; import org.muses.jeeplatform.core.constants; import org.muses.jeeplatform.core.excelviewwrite; import org.muses.jeeplatform.core.javaemailsender; import org.muses.jeeplatform.model.entity.user; import org.muses.jeeplatform.service.userservice; import org.muses.jeeplatform.utils.datejsonvalueprocessor; import org.muses.jeeplatform.utils.dateutils; import org.springframework.beans.factory.annotation.autowired; import org.springframework.data.domain.page; import org.springframework.data.domain.sort; import org.springframework.stereotype.controller; import org.springframework.ui.model; import org.springframework.web.bind.annotation.requestmapping; import org.springframework.web.bind.annotation.requestparam; import org.springframework.web.bind.annotation.responsebody; import org.springframework.web.servlet.modelandview; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import java.io.printwriter; import java.util.*; /** * created by nicky on 2017/7/29. */ @requestmapping("/user") @controller public class usercontroller extends basecontroller{ @autowired userservice userservice; /** * 查询所有管理员信息并分页显示 * @param request * @param response * @param model * @return */ @requestmapping(value = "/queryall",produces = "application/json;charset=utf-8") @responsebody public modelandview findall(httpservletrequest request, httpservletresponse response, model model){ //当前页 string pageindexstr = request.getparameter("pageindex"); //每一页的页数 int pagesize = constants.page_size; modelandview mv = this.getmodelandview(); page<user> userpage; if(pageindexstr==null||"".equals(pageindexstr)){ pageindexstr = "0"; } int pageindex = integer.parseint(pageindexstr); userpage = userservice.findall(pageindex+1, pagesize, sort.direction.asc,"id"); mv.addobject("totalcount",userpage.gettotalelements()); mv.addobject("pageindex",pageindex); // jsonconfig cfg = new jsonconfig(); // cfg.setexcludes(new string[]{"handler","hibernatelazyinitializer"}); jsonconfig jcg = new jsonconfig(); jcg.registerjsonvalueprocessor(date.class, new datejsonvalueprocessor("yyyy-mm-dd")); jsonarray jsonarray = jsonarray.fromobject(userpage.getcontent(),jcg); //system.out.println(jsonarray.tostring()); mv.addobject("users",jsonarray.tostring()); mv.setviewname("admin/user/sys_user_list"); return mv; } }
【前端页面实现】
页面view实现,引用 jquery.pagination.js (分页js),跟pagination.css(分页样式css)。
可以去这里下载:
<%@ page contenttype="text/html; charset=utf-8" pageencoding="utf-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> <% string path = request.getcontextpath(); string basepath = request.getscheme()+"://"+request.getservername()+":"+request.getserverport()+path+"/"; %> <!doctype html> <html lang="zh-cn"> <head> <base href="<%=basepath %>" rel="external nofollow" > <meta charset="utf-8" /> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="viewport" content="width=device-width,initial-scale=1"> <title>insert title here</title> <!-- bootstrap样式--> <link type="text/css" rel="stylesheet" href="<%=basepath%>plugins/page/css/bootstrap-3.3.5.min.css" rel="external nofollow" /> <!-- jquery.pagination所需css --> <link type="text/css" rel="stylesheet" href="<%=basepath%>plugins/page/css/pagination.css" rel="external nofollow" /> <script type="text/javascript" src="<%=basepath%>plugins/page/js/jquery.min.js"></script> <!-- jquery.pagination所需js 注意必须放在jquery.js后面 --> <script type="text/javascript" src="<%=basepath%>plugins/page/js/jquery.pagination.js"></script> <script type="text/javascript"> /** 分页操作,使用jquery.pagination插件 add by nicky 20170729 start **/ //当前页 var pageindex = number(${pageindex}); //数据量 var totalcount = number(${totalcount}); $(document).ready(function () { //加入分页的绑定 $("#pagination").pagination(totalcount, { callback : pageselectcallback, prev_text : '< 上一页', next_text: '下一页 >', items_per_page : 6, num_display_entries : 6, current_page : pageindex, num_edge_entries : 1, link_to: "user/queryall?pageindex=__id__" //分页的js中会自动把"__id__"替换为当前的数。0 }); var html = ""; var data = ${users}; $.each(data,function(idx,obj){ var id = obj.id; var username = obj.username; var mark = obj.mark; var phone = obj.phone; var email = obj.email; var lastlogin = obj.lastlogin; var loginip = obj.loginip; html += "<tr><td><input type='checkbox' name='id' id='id' value=" + id + " /></td>" + "<td>"+id+"</td>"+ "<td>"+username+"</td>"+ "<td>"+mark+"</td>"+ "<td>"+phone+"</td>"+ "<td>"+email+"</td>"+ "<td>"+lastlogin+"</td>"+ "<td>"+loginip+"</td>"+ "<td><a href='javascript:openeditdialog("+id+");' class='bouncein'>配置角色</a>"+ "</tr>"; }); $("#content").append(html); }); //这个事件是在翻页时候用的 function pageselectcallback(index, jq) { } /** 分页操作,使用jquery.pagination插件 add by nicky 20170729 end **/ //checkbox的全选/反选 var ischeckall = false; function docheck(){ if(ischeckall){ $("input[type='checkbox']").each(function(){ this.checked = false; }); ischeckall = false; }else{ $("input[type='checkbox']").each(function(){ this.checked = true; }); ischeckall = true; } } </script> </head> <body> <br> <div class="container-fluid"> <div class="row"> <div class="col-xs-12 col-md-12"> <div class="panel panel-default"> <div class="panel-body"> <form class="form-inline"> <input type="button" class="btn btn-default" value="发送邮件" onclick="sendemail();" /> <input type="button" class="btn btn-default" value="发送短信" onclick="sendsms();" /> <input type="button" class="btn btn-default" value="导出excel表" onclick="exportexcel();" /> <br><br><!-- <input type="text" class="form-control" id="keyword" placeholder="请输入关键词"> 日期从<input type="text" class="form-control" placeholder="请输入开始日期" value="${startdate }" id="startdate" name="startdate" onclick="wdatepicker({datefmt:'yyyy-mm-dd' ,maxdate:'#f{$dp.$d(\'enddate\')}'});"/> 到<input type="text" class="form-control" placeholder="请输入结束日期" value="${enddate }" id="enddate" name="enddate" onclick="wdatepicker({datefmt:'yyyy-mm-dd' ,mindate:'#f{$dp.$d(\'startdate\')}'});" /> <input type="button" class="btn btn-default" value="search" onclick="dosearch();"/>--> </form> <table class="table" id="mtable"> <thead> <tr> <th><input type="checkbox" onclick="docheck();" /></th> <th>序号</th> <th>用户名</th> <th>描述</th> <th>手机</th> <th>邮箱</th> <th>最近登录</th> <th>上次登录ip</th> <th>操作</th> </tr> </thead> <tbody id="content"> </tbody> </table> <div id="pagination" class="pagination"></div> <!-- demo --> </div> </div> </div> </div> </div> </body> </html>
前端页面展示:
ok,本博客是基于一款正在开发中的github开源项目的,项目代码地址:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。