SSM framework-Implementing paging and search paging

Source: Internet
Author: User
Tags prev table name java web

Paging is a common feature of Java Web Projects, and a simple paging operation and a search page in spring MVC were recorded yesterday. The frame used is (mybatis+springmvc+spring).


First we need a paging tool class: 1. Paging

Import java.io.Serializable; /** * Paging * */public class Page implements Serializable {private static final long Serialversionuid = 3198048449643774

	660L; private int pagenow = 1; Current page private int pageSize = 4; Shows the number of records per page private int totalcount; Total number of record bars private int totalpagecount; The total number of pages @SuppressWarnings ("unused") private int startpos; Start position, starting from 0 @SuppressWarnings ("unused") Private Boolean hasfirst;//whether there is a home @SuppressWarnings ("unused") private Boole An haspre;//whether there is a previous page @SuppressWarnings ("unused") Private Boolean hasnext;//whether there is a next page @SuppressWarnings ("unused") privat E Boolean haslast;//whether there is a last page/** * pass through the constructor function the total number of records and the current page * @param totalcount * @param pagenow */Public page (int totalcount, int pagenow)
		{this.totalcount = TotalCount;
	This.pagenow = Pagenow; }/** * Get total pages, total pages = Total Records/Total pages * @return */public int gettotalpagecount () {totalpagecount = Gettotalcount ()/GE
		Tpagesize (); Return (totalcount% pageSize = = 0)? TotalpaGecount:totalpagecount + 1;
	} public void Settotalpagecount (int totalpagecount) {this.totalpagecount = Totalpagecount;
	} public int Getpagenow () {return pagenow;
	} public void Setpagenow (int pagenow) {this.pagenow = Pagenow;
	} public int getpagesize () {return pageSize;
	} public void SetPageSize (int pageSize) {this.pagesize = pageSize;
	} public int Gettotalcount () {return totalcount;
	} public void Settotalcount (int totalcount) {this.totalcount = TotalCount;
	}/** * Gets the initial position of the selection record * @return */public int getstartpos () {return (pageNow-1) * pageSize;
	} public void Setstartpos (int startpos) {this.startpos = startpos;
	}/** * is the first page * @return */public boolean Ishasfirst () {return (Pagenow = = 1)? false:true;
	The public void Sethasfirst (Boolean hasfirst) {this.hasfirst = Hasfirst; }/** * Whether there is a home page * @return */public boolean ishaspre () {///If there is a first page there is the previous one, because there is a home is not the first return Ishasfirst ()? True: False
	The public void Sethaspre (Boolean haspre) {this.haspre = Haspre;  }/** * If there is a next page * @return */public boolean ishasnext () {//If there is a last page, there will be next, because there is a last page return Ishaslast ()? True
	: false;
	The public void Sethasnext (Boolean hasnext) {this.hasnext = Hasnext; }/** * Is there a last page * @return */public boolean ishaslast () {//If it is not the last one, the last return (Pagenow = = Gettotalcount ())?
	False:true;
	The public void Sethaslast (Boolean haslast) {this.haslast = Haslast;
 }

}

With this tool class, first write the SQL statement in the MyBatis xxxxmapper.xml configuration file, as follows:

  <!--paged SQL statement--
  <select id= "Selectproductsbypage" resultmap= "return value type" >
    select 
    * from
    table name WHERE user_id = #{userid,jdbctype=integer} limit #{startpos},#{pagesize} 
  </select>
  <!--total number of records obtained-- >
  <select id= "Getproductscount" resulttype= "Long" >
    select COUNT (*) from table name WHERE user_id = #{userid, Jdbctype=integer} 
  </select>


Here we can see that 2 <select> need to pass 3 and one parameter respectively, at this time in the corresponding DAO file Ixxxxdao to write the interface to write the corresponding method, the method name and mapper.xml in the id attribute values consistent:

    /**
     * Use annotation method to pass in multiple parameters, user product pagination, query by login User ID
     * @param page
     * @param userId
     * @return Startpos},#{pagesize} 
     */Public
    list<products> selectproductsbypage (@Param (value= "startpos") Integer Startpos, @Param ( Value= "pageSize") integer pageSize, @Param (value= "userid") integer userId);
    
    /**
     * Obtain product quantity information, query by login User ID
     * @param userId
     * @return */public
    Long Getproductscount (@Param ( Value= "userid") Integer userid);


After the interface definition is complete, you need to write the appropriate business interface and implementation method, define such a method in the interface, and then overwrite the implementation class:

/**
	 * Page Show Item
	 * @param request
	 * @param model
	 * @param loginuserid
	*/void Showproductsbypage (httpservletrequest request,model model,int loginuserid);

The next method in the implementation class is to invoke the DAO layer and accept the parameters passed in by the controller, to handle the business logic, request is used to get the front-end incoming parameters, model is used to return the processing results to the JSP page.

@Override public
void Showproductsbypage (HttpServletRequest request, Model Model,int Loginuserid) {
	String Pagenow = Request.getparameter ("Pagenow");

	Page page = null;

	list<productwithblobs> products = new arraylist<productwithblobs> ();

	int totalcount = (int) productdao.getproductscount (loginuserid);

	if (Pagenow! = null) {
		page = new page (TotalCount, Integer.parseint (Pagenow));
		Allproducts = This.productDao.selectProductsByPage (Page.getstartpos (), Page.getpagesize (), Loginuserid);
	} else {
		page = new page (totalcount, 1);
		Allproducts = This.productDao.selectProductsByPage (Page.getstartpos (), Page.getpagesize (), Loginuserid);
	}

	Model.addattribute ("Products", products);
	Model.addattribute ("page", page);
}


Next is the controller's writing, when the user needs to jump to the actual product page, it needs to go through the corresponding method of the controller processing, the process is to call the business layer method to complete, and then return the results to the JSP dynamic display, the server side generated a good page after the client (browser) reality, This is an MVC process.

/**
 * Initialize my products list JSP page with paging function
 * 
 * @param request
 * @param model
 * @return */
@ Requestmapping (value = "Map Path", method = requestmethod.get) public
String showmyproduct (httpservletrequest request, Model model) {
	//Get loginuser
	User loginuser = (user) request.getsession () in session. GetAttribute ("Loginuser") ;
	Determines if the session is invalid
	if (Loginuser = = NULL | | ". Equals (Loginuser)) {
		return" redirect:/";
	}

	int loginuserid = Loginuser.getuserid ();
	The productservice here is an injected Iproductservice interface object
	this.productService.showProductsByPage (request, model, Loginuserid);

	Return "Jump to JSP path";
}

JSP page Accept Part I will not write, everyone is the same, that is, the combination of Jstl and El to write, (in the loop output also made a judgment, if the parameters are empty, then the output is no commodity, only the parameters are not empty, only the time to loop output, use <<c:when Test= "${}" > Combine <c:otherwise>), here are only the relevant code for pagination:

<!--paging function start-to-<div align= "center" > <font size= "2" > Total ${page.totalpagecount} page </font> <f Ont size= "2" > ${page.pagenow} page </font> <a href= "myproductpage?pagenow=1" > Home </a> &LT;C:CHOOSE&G
			T <c:when test= "${page.pagenow-1 > 0}" > <a href= "myproductpage?pagenow=${page.pagenow-1}" > Prev &LT;/A&G
			T </c:when> <c:when test= "${page.pagenow-1 <= 0}" > <a href= "myproductpage?pagenow=1" > Prev </a > </c:when> </c:choose> <c:choose> <c:when test= "${page.totalpagecount==0}" > < A href= "Myproductpage?pagenow=${page.pagenow}" > Next </a> </c:when> <c:when test= "${page.pagenow + 1 < Page.totalpagecount} "> <a href=" Myproductpage?pagenow=${page.pagenow + 1} "> Next </a> </c:when&
			Gt <c:when test= "${page.pagenow + 1 >= page.totalpagecount}" > <a href= "Myproductpage?pagenow=${page.totalpag Ecount}"> Next </a> </c:when> </c:choose> <c:choose> <c:when test=" ${page.totalpagecount==0}
				"> <a href=" Myproductpage?pagenow=${page.pagenow} "> Last </a> </c:when> <c:otherwise> <a href= "Myproductpage?pagenow=${page.totalpagecount}" > Last </a> </c:otherwise> </c:choose> & lt;/div> <!--paging function End---


2. Query paging about query paging , the approximate process is exactly the same, but the third parameter (above is Loginuserid) needs to accept user input parameters, so we need to accept the user input parameters in the controller (page < input> use get to pass the parameter, and then add it to the session, you can complete the query paging (here because of the "next page" in the cause of the hyperlink, using a different JSP page processing pagination and search paging, Temporarily did not find in a JSP page to complete the method, there is a duplicate code, where the code is the output of the code, can be taken out separately, and then a <include> tag loaded into the desired JSP page can be, so as to avoid code duplication):

The code for the controller is given here as a reference:

/** * Search Products by Product name * @param request * @param model * @return */@RequestMapping (value = "Map Address", method = Reques tmethod.get) public String searchforproducts (HttpServletRequest request, model model) {HttpSession session = REQUEST.G

		Etsession ();

		String param = request.getparameter ("param");

		String condition = (string) session.getattribute ("condition");
			First determine if the condition in the session is empty if (condition = = null) {condition = new String ();
			Session.setattribute ("condition", condition); If the condition in the session is empty, then determine if the passed parameter is empty, and if it is empty, jump to the search results page if (param = = NULL | |
			". Equals (param)) {return" Private/space/productsearchresult "; }}//If the session is not empty and the incoming search condition param is not empty, then assign param to condition if (param! = null &&! ("".
			Equals (param))) {condition = param;
		Session.setattribute ("condition", condition);

		}//Use the condition attribute value in session as the query condition This.productService.showSearchedProductsByPage (request, model, condition);
	Return "page to jump";
 }

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.