Ajax paging Spring MVC + Hibernate

Source: Internet
Author: User


1. Add public classes, methods, code

1. Pagination class: Page.java

Package Cn.com.aperfect.sso.base.dao;import Java.util.arraylist;import Java.util.list;public class Page<T> {// Current page private int currentpage;//record offset private int offset;//total pages private int totalspage;//Each page shows the number of record bars private int pagesize;//total record The number of private int totalscount;//query Returns the result private list<t> result = new arraylist<t> ();//Paging link private String URI;PUBL IC page () {}public page (int currentpage, int pageSize) {this.currentpage = Currentpage;this.pagesize = PageSize; This.offset = (currentPage-1) *pagesize;} Public String GetURI () {return URI;} public void Seturi (String uri) {This.uri = URI;} public int getcurrentpage () {return currentpage;} public void setcurrentpage (int currentpage) throws Exception {if (CurrentPage < 0) {currentpage = 0;} This.currentpage = currentpage;} public int gettotalspage () {try {if (totalscount% pageSize = = 0) {totalspage = Totalscount/pagesize;} else {Totalspage = (totalscount/pagesize) + 1;}} catch (Exception e) {throw new RuntimeException (e);} Return TotalSpage;} public void settotalspage (int totalspage) {if (Totalspage < 0) {totalspage = 0;} This.totalspage = Totalspage;} public int getpagesize () {return pageSize;} public void setpagesize (int pageSize) {if (pageSize <= 0) {pageSize = 20;} This.pagesize = pageSize;} public int Gettotalscount () {return totalscount;} public void Settotalscount (int totalscount) {if (Totalscount < 0) {Totalscount = 0;} This.totalscount = Totalscount;} Public list<t> GetResult () {return result;} public void Setresult (list<t> result) {This.result = result;} public int GetOffset () {return offset;} public void SetOffset (int offset) {this.offset = offset;}}
2. Dao/daoimpl of the public

DAO

/** * <b>function:</b> incoming query statement and query parameter name key corresponds to value,page specify CurrentPage and pagesize * @param queryhql query statement * @param Parammap parameter * @param page current and several data per page * @throws Exception */public page<t> showpage (String queryhql,string counthql, Map<string, object> parammap,int currentpage, int pageSize) throws Exception;
IMPL

Public page<t> showpage (string queryhql, String counthql, map<string, object> parammap, int currentpage, int p Agesize) throws Exception {page<t> Page = new Page<t> (currentpage, pageSize); try {int datacount = queryForInt ( COUNTHQL, Parammap);p Age.setresult (queryForList (QUERYHQL, Parammap, Page.getoffset (), pageSize)); Page.settotalscount (Datacount);} catch (Exception e) {throw new RuntimeException (e);} return page;} Private final int queryForInt (String queryinthql,map<string, object> parammap) {Query query = this.getsession (). CreateQuery (QUERYINTHQL); setqueryparametervalues (parammap, query); int result = Integer.parseint (query.uniqueresult (). toString ()); return result;} Private final list<t> queryForList (String queryhql,map<string, object> parammap, int offset,int pageSize) { Query query = this.getsession (). CreateQuery (QUERYHQL); setqueryparametervalues (parammap, query); if (offset>=0) { Query.setfirstresult (offset);} if (pagesize>0) {Query.setmaxresults(pageSize);} return Query.list (); }private final void Setqueryparametervalues (map<string, object> parammap,query Query) {if ( Collectionutil.isempty (Parammap)) return; for (entry<string, object> entry:paramMap.entrySet ()) { Query.setparameter (Entry.getkey (), Entry.getvalue ());}}

2. Code (Controller)

The controller has two request methods respectively, the requested address is not the same.

One is used to initialize the page request, and the other is the AJAX request when paging.

(The first request returns the entire page, and the AJAX request returns only one extracted *table.jsp, so two requests, just a different JSP.) Just use JS to replace the original page of the table with the new only)

The method body is the same.

@Controller @requestmapping ("/srmuser") public class Srmusercontroller {@Resourceprivate isrmuserservice srmuserservice;private void Dosearch (HttpServletRequest request, httpservletresponse response) throws Exception{int CurrentPage = Servletrequestutils.getintparameter (Request, "CurrentPage", 1); int pageSize = Servletrequestutils.getintparameter (Request, "PageSize", 10);//foreground data is passed to the background query string enterprisename = Servletrequestutils.getstringparameter (Request, "Enterprisename"); String VendorName = servletrequestutils.getstringparameter (Request, "VendorName"); String userName = servletrequestutils.getstringparameter (Request, "UserName"); String status = Servletrequestutils.getstringparameter (Request, "status"); String fromcreatedate = servletrequestutils.getstringparameter (Request, "fromcreatedate"); String tocreatedate = servletrequestutils.getstringparameter (Request, "tocreatedate"); page<srmuser> page = srmuserservice.searchuserlist (enterprisename,vendorname,username,status,fromcreatedate , toCreateDate, CurrentPage, pageSize);//Data return to foreground request.setattribute ("Enterprisename", enterprisename); Request.setattribute ("VendorName", VendorName), Request.setattribute ("UserName", UserName); Request.setattribute (" Status ", status), Request.setattribute (" Fromcreatedate ", Fromcreatedate), Request.setattribute (" Tocreatedate ", tocreatedate) Request.setattribute ("Tocreatedate", tocreatedate); Request.setattribute ("UserListDto", Page.getresult ()); Request.setattribute ("pageentity", page);} @RequestMapping ("/searchuser") public String Searchuser (httpservletrequest request, httpservletresponse response) Throws Exception {Dosearch (request, response); return "/srm_management/srmuser_manage";} @RequestMapping ("/ajaxsearchuser") public String Ajaxsearchuser (httpservletrequest request, HttpServletResponse Response) throws Exception {Dosearch (request, response); return "/srm_management/inc/srmuser_table";}}

Specific query Code

@Overridepublic page<srmuser> getuserlist (String enterprisename, String vendorname,string userName, string Status, String fromcreatedate,string tocreatedate, int currentpage, int pageSize) throws Exception {page<srmuser> p age = null; StringBuffer sbhql = new StringBuffer (); StringBuffer counthql = new StringBuffer (); map<string, object> parammap = new hashmap<string, object> (); try {sbhql.append ("from Srmuser U where 1=1"); Counthql.append ("SELECT count (*) from Srmuser u where 1=1"); if (! Stringutil.isempty (Enterprisename)) {Sbhql.append ("and U.enterprise.enterprisename like:enterprisename"); Counthql.append ("and U.enterprise.enterprisename like:enterprisename");p arammap.put ("enterprisename", "%" + enterprisename+ "%");} if (! Stringutil.isempty (VendorName)) {Sbhql.append ("and U.userid in ("); Sbhql.append ("Select UserId from Srmuservendor s whe Re S.vendorid in ("), Sbhql.append (" Select VendorID from Srmvendor v where v.vendorname like:vendorname) "); Counthql.apPend ("and U.userid in ("), Counthql.append ("Select UserId from Srmuservendor s where S.vendorid in ("); Counthql.append ("Se Lect VendorID from Srmvendor v where v.vendorname like:vendorname) ");p arammap.put (" VendorName ","% "+vendorname+"% ");} if (! Stringutil.isempty (UserName)) {Sbhql.append ("and U.username like:username"); Counthql.append ("and u.username like: UserName ");p arammap.put (" userName ","% "+username+"% ");} if (! Stringutil.isempty (status) {Sbhql.append ("and u.status =: status"), Counthql.append ("and u.status =: status");p Aramma P.put ("Status", Integer.parseint (status));} if (! Stringutil.isempty (fromcreatedate)) {Sbhql.append ("and u.createdate >=: Fromcreatedate"); CountHQL.append ("and U.createdate >=: Fromcreatedate ");p arammap.put (" Fromcreatedate ", Fromcreatedate);} if (! Stringutil.isempty (tocreatedate)) {Sbhql.append ("and U.createdate <: Tocreatedate"); Counthql.append ("and U.createdate <: Tocreatedate ");//tocreatedate to add a day java.util.Date Date = new SimpleDateFormat ("Yyyy-mm-dd"). Parse (tocreatedate);     Calendar calendar = new GregorianCalendar ();     Calendar.settime (date);    Calendar.add (calendar.date,1); Date= Calendar.gettime (); Parammap.put ("Tocreatedate", date);} Sbhql.append ("ORDER by U.userid ASC");p age = ShowPage (Sbhql.tostring (), counthql.tostring (), Parammap, CurrentPage, pag Esize);

3. Front-desk JSP, etc.

The JSP is divided into two parts, part of the overall page when the first request is complete.

The other part is that *_table.jsp is the table to be paged.

As long as the whole inside Out *_table.jsp page, and then the overall page inside the reference *_table.jsp page.


Replace the table with the AJAX request with the following, the <span> is the identity to replace when the AJAX request succeeds

  <span id= "Resourcespan" >  <jsp:include page= "inc/srmuser_table.jsp"/>  </span>

Backstage will return the entire *_table.jsp page to the front desk <span> inside.

*.table.jsp

<%@ page language= "java" pageencoding= "UTF-8"%><%@ taglib uri= "Http://java.sun.com/jstl/core_rt" prefix= "C" %><table class= "Details" ><tr class= "NOTICCLSSRM" ><td> Enterprise </td><td> user name </td> <td> Creator </td><td> creation time </td><!--<td> last editor </td><td> last update time </td>- -><td> status </td></tr><c:foreach var= "Userdto" items= "${requestscope.userlistdto}" ><tr ><td>${userdto.enterprise.enterprisename}</td><td>${userdto.username}&LT;/TD&GT;&LT;TD >${userdto.creatorname}</td><td><fmt:formatdate value= "${userdto.createdate}" pattern= " Yyyy-mm-dd "/> </td><%--<td>${userdto.editorname}</td><td><fmt:formatdate value= "${userdto.updatedate}" pattern= "Yyyy-mm-dd"/> </td>--%><td><c:if test= "${userdto.status==0} "> Start </c:if><c:if test=" ${userdto.status==1} "> Freeze </c:if><c:if test=" ${userdto.status==2} "> Delete </c:if></td></tr></c:foreach></table><jsp:include page=". /.. /commons/page_ajax.jsp "/><script type=" Text/javascript ">//Paging jump var totalspage = ' ${pageentity.totalspage} ' if (totalspage = = ") Totalspage = 1;function Ajaxgotopage (currentpage) {if (currentpage = = NULL | | currentpage = =" ") Re Turn;if (IsNaN (currentpage)) return;if (CurrentPage < 1) currentpage = 1;else if ((CurrentPage > Totalspage) | | (Currentpage==${pageentity.currentpage})) Return;var Resourcespan = $ ("#resourceSpan"); resourcespan.html ("<br/> "); $.ajax ({url: ' ${ PageContext.request.contextPath}/v/srmuser/ajaxsearchuser ', type: ' Post ', Data:{currentpage:currentpage, enterprisename:$ ("#enterpriseName"). Val (), vendorname:$ ("#vendorName"). Val (), username:$ ("#userName"). Val (), status:$ ("#status"). Val (), fromcreatedate:$ ("#fromCreateDate"). Val (), tocreatedate:$ ("#toCreateDate"). Val ()},datatype: ' Text ', Timeout:60000,error:function (e) {alert (e);},success:function (Result) {resourcespan.html ( result);}}); function Gotopagebyinput () {var Currentpage=document.getelementbyid (' Goinput '). Value;ajaxgotopage (ParseInt ( currentpage));} </script>

page_ajax.jsp

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%>
<%@ taglib prefix= "C" uri= "Http://java.sun.com/jsp/jstl/core"%><style><span style= "White-space:pre" ></span>.gosearchbutton{background:url (<c:url value= '/resources/images/ok.gif '/>); border:0 none; height:19px;margin:0 0 0 5px;text-indent:-999px;width:37px;} <span style= "White-space:pre" ></span>div.yk-pager {text-align:right;padding:3px 0px;margin:3px 0px; Color: #666666;} <span style= "White-space:pre" ></span>div.yk-pager a{color: #036CB4; margin-right:2px;padding:2px 5px; text-decoration:none;border:1px solid #929196;} <span style= "White-space:pre" ></span>div.yk-pager a:hover {padding:2px 5px;margin-right:2px; Background-color: #ccdaf3; border: #a0a0a0 1px solid;} <span style= "White-space:pre" ></span>div.yk-pager a:active {padding:2px 5px;margin-right:2px; Background-color: #ccdaf3; border: #a0a0a0 1px solid;} <span style= "White-space:pre" ></span>div.yk-pager span.current {font-weight:bold;color: #FFFFFF;padding:2px 5px;margin-right:2px;background-color: #6390cb, border:1px solid #3d68a0}<span style= "White-space:pre" ></span>div.yk-pager span.disabled {color: #ccc; margin-right:2px;border:1px solid #f3f3f3;p adding:2px 5px;} <span style= "White-space:pre" ></span>div.yk-pager. goinput{border:1px solid #99bbe8; color: #000000; font-family:tahoma,simsun,arial;height:18px;margin:0 5px;text-align:center;vertical-align:top;width:30px;} <span style= "White-space:pre" ></span>div.yk-pager. Gobutton{background:url (skin/ok.gif); border:0 None ; height:19px;margin:0 0 0 5px;text-indent:-999px;width:37px;} </style><div class= "Yk-pager" ><a href= "javascript:ajaxgotopage (1);" > Home </a><a href= "Javascript:ajaxgotopage (${pageentity.currentpage-1}); > prev </a> <a href= "Javascript:ajaxgotopage (${pageentity.currentpage+1}); > next page? </a><a href= "Javascript:ajaxgotopage (${pageentity.totalspage}); > End </a> Total ${pageentity.totalscount}, section ${pageentity.currentpage}/${pageentity.totalspage}, to <input size=2 id= "goinput" value= "/> page, <input Type= "button" class= "Gobutton" onclick= "gotopagebyinput ();" /></div>
Ok.gif








Ajax paging Spring MVC + Hibernate

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.