SpringDataJpa+SpringMVC+Jquery.pagination.js实现分页的方法
小编给大家分享一下Spring Data Jpa+SpringMVC+Jquery.pagination.js实现分页的方法,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
创新互联专注于企业成都全网营销推广、网站重做改版、甘德网站定制设计、自适应品牌网站建设、H5技术、电子商务商城网站建设、集团公司官网建设、外贸网站建设、高端网站制作、响应式网页设计等建站业务,价格优惠性价比高,为甘德等各大城市提供网站开发制作服务。
介绍一下Spring Data框架
spring Data : Spring 的一个子项目。用于简化数据库访问,支持NOSQL 和 关系数据存储。
下面给出SpringData 项目所支持 NoSQL 存储:
* MongoDB (文档数据库)
* Neo4j(图形数据库)
* redis(键/值存储)
* Hbase(列族数据库)
SpringData 项目所支持的关系数据存储技术:
* JDBC
* JPA
JPA Spring Data : 致力于减少数据访问层 (DAO) 的开发量。开发者只要写好持久层接口就好,然后其它的框架会帮程序员实现。
开发步骤:
本项目是采用maven的,所以可以参考一下我的maven配置:
muses org.muses 1.0-SNAPSHOT 4.0.0 jeeplatform-admin war jeeplatform-admin Maven Webapp http://maven.apache.org 4.1.5.RELEASE 1.4.2.RELEASE 1.6.2.RELEASE 4.3.8.Final 1.2.3 4.7.2 1.0.9 3.7 org.muses jeeplatform-core ${jeeplatform.core.version} org.muses jeeplatform-common 1.0-SNAPSHOT org.muses jeeplatform-oss ${jeeplatform.oss.version} org.muses jeeplatform-upms 1.0-SNAPSHOT javax.servlet servlet-api 2.5 provided jstl jstl 1.2 taglibs standard 1.1.2 log4j log4j ${log4j.version} commons-beanutils commons-beanutils 1.8.3 commons-collections commons-collections 3.2.1 net.sf.ezmorph ezmorph 1.0.6 commons-lang commons-lang 2.5 commons-logging commons-logging 1.2 net.sf.json-lib json-lib 2.4 jar jdk15 compile mysql mysql-connector-java ${mysql.version} commons-io commons-io 2.0.1 commons-fileupload commons-fileupload 1.2.2 org.springframework spring-core ${spring.version} org.springframework spring-beans ${spring.version} org.springframework spring-context ${spring.version} org.springframework spring-context-support ${spring.version} org.springframework spring-jdbc ${spring.version} org.springframework spring-tx ${spring.version} org.springframework spring-test ${spring.version} test org.springframework spring-web ${spring.version} org.springframework spring-aop ${spring.version} org.aspectj aspectjweaver 1.6.10 org.springframework spring-webmvc ${spring.version} org.springframework spring-orm ${spring.version} org.springframework.data spring-data-jpa ${spring-data-jpa.version} org.springframework.data spring-data-commons ${spring-data-commons.version} org.hibernate.javax.persistence hibernate-jpa-2.1-api 1.0.0.Final org.hibernate hibernate-core ${hibernate.version} org.hibernate hibernate-entitymanager ${hibernate.version} org.slf4j slf4j-api 1.6.1 net.sf.ehcache ehcache-core 2.5.0 org.hibernate hibernate-ehcache ${hibernate.version} com.alibaba druid ${druid.version} org.apache.shiro shiro-all ${shiro.version} org.apache.velocity velocity 1.6 org.apache.velocity velocity-tools 2.0 org.apache.lucene lucene-core ${lucene.version} org.apache.lucene lucene-analyzers-common ${lucene.version} org.apache.lucene lucene-queryparser ${lucene.version} org.apache.lucene lucene-memory ${lucene.version} org.apache.lucene lucene-highlighter ${lucene.version} org.wltea.analyzer IKAnalyzer 2012FF_u1 system ${basedir}/src/main/webapp/WEB-INF/lib/IKAnalyzer2012FF_u1.jar log4j log4j ${log4j.version} commons-beanutils commons-beanutils 1.8.3 commons-collections commons-collections 3.2.1 net.sf.ezmorph ezmorph 1.0.6 commons-lang commons-lang 2.5 commons-logging commons-logging 1.2 net.sf.json-lib json-lib 2.4 jar jdk15 compile org.apache.poi poi ${poi.version} com.sun.mail javax.mail 1.5.6 jeeplatform-admin
设计好数据库,编写一个实体类:
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 Setroles; @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 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 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 PagefindAll(int pageNo, int pageSize, Sort.Direction dir, String str){ PageRequest request = buildPageRequest(pageNo, pageSize, dir, str); Page 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(); PageuserPage; 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)。
可以去这里下载:https://www.jb51.net/article/105013.htm
<%@ 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+"/"; %>" rel="external nofollow" > Insert title here plugins/page/css/bootstrap-3.3.5.min.css" rel="external nofollow" /> plugins/page/css/pagination.css" rel="external nofollow" />
序号 用户名 描述 手机 邮箱 最近登录 上次登录IP 操作
前端页面展示:
以上是“Spring Data Jpa+SpringMVC+Jquery.pagination.js实现分页的方法”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注创新互联行业资讯频道!
网站名称:SpringDataJpa+SpringMVC+Jquery.pagination.js实现分页的方法
链接地址:http://scyanting.com/article/piogdo.html