Pagination & sorting in jsp’s with the displaytag taglib & spring

February 13th, 2009 | Tags: , , ,

I hate writing pagination code. Infact I hate it so much, I try not to paginate my lists at all. ( I know, i know, very bad on my part) :) . Writing pagination code totally destroys the code reuse in an application, developers generally just copy paste the very same pagination code all over the place over and over again. Not to mention decorating such pagination displays is a pain in the ass as well. So while searching for a more concrete solution to my problem I stumbled upon displaytag.

Display tag is by far the most comprehensive pagination solution that I have ever come across. Not only is the library extremely stable, it’s rich of features and customizations. I haven’t yet run across a scenario where display tag didn’t fulfill my needs. And you don’t need to do anything extra to get it working in your webapp. I’m going to develop a small example which will show a list of 20 user’s.

Because of my love for spring, i’ll use a Spring controller to pass data onto my jsp. You don’t really NEED to use spring with displaytag per se since displaytag can pick up the list to display from anywhere, session, context, page and you can set this list anywhere as well.

My controller first :

package com.codercorp.displaytag;

//imports
@Controller
@RequestMapping("/displaytag.html")
public class DisplaytagController {

	private static List<User>	userList;

	static {
		userList = new ArrayList<User>(20);
		userList.add(new User(1, "Gaurav Arora", "gaurav@myemail.com", "+91-98119-09880"));
		userList.add(new User(2, "Bernard Shaw", "bernard@myemail.com", "+91-92119-09880"));
		userList.add(new User(3, "Aurora Aurealis", "aurora@myemail.com", "+91-93119-09880"));
		userList.add(new User(4, "James Lock", "james@myemail.com", "+91-98114-09880"));
		userList.add(new User(5, "Karl love", "karl@myemail.com", "+91-98169-09880"));
		userList.add(new User(6, "George jungle", "george@myemail.com", "+91-98819-09880"));
		userList.add(new User(7, "Switch blade", "switch@myemail.com", "+91-98118-09880"));
		userList.add(new User(8, "Gold flake", "gold@myemail.com", "+91-98119-09380"));
		userList.add(new User(9, "Susan Anthony", "susan@myemail.com", "+91-98113-09880"));
		userList.add(new User(10, "Arm Guard", "armg@myemail.com", "+91-98119-02880"));
		userList.add(new User(11, "Raju Gentleman", "raju@myemail.com", "+91-98319-09880"));
		userList.add(new User(12, "Rajat Ghandhi", "rajat@myemail.com", "+91-98519-09880"));
		userList.add(new User(13, "Niketa Shyam", "niketa@myemail.com", "+91-98719-09880"));
		userList.add(new User(14, "G. Mahesh", "mahesh@myemail.com", "+91-98118-09880"));
		userList.add(new User(15, "Yogvinder Singh", "yogi@myemail.com", "+91-99119-09880"));
		userList.add(new User(16, "Eklavya", "eklavya@myemail.com", "+91-98119-00880"));
		userList.add(new User(17, "Asus shyam", "asus@myemail.com", "+91-98119-09680"));
		userList.add(new User(18, "Jack donneley", "jack@myemail.com", "+91-98119-01880"));
		userList.add(new User(19, "Donald McDonald", "donald@myemail.com", "+91-98119-03880"));
		userList.add(new User(20, "Azure Aloha", "azure@myemail.com", "+91-98119-09890"));
	}

	@RequestMapping(method = RequestMethod.GET)
	public String showPage(HttpServletRequest request, HttpSession session) {
		Map paramMap = WebUtils.getParametersStartingWith(request, "d-");
		if (paramMap.size() == 0) {
			WebUtils.setSessionAttribute(request, "userList", userList);
		}
		return "displaytag";
	}
}

The static part populates the userList with dummy User objects. Line #36 is used to decide if the list should be set in the session or not. displaytag sends it’s pagination and sorting data using parameters that start with “d-”. If any such params exist in our request we ignore setting the list in the session because it is already set. However, on a new request, when no params are set, the list is put into the session again which is ideal for us.

Now the display:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="display" uri="http://displaytag.sf.net"%>
<body>
<head>
<link rel="stylesheet" href="css/screen.css" type="text/css" />
</head>
<display:table uid="user" name="sessionScope.userList" defaultsort="1"
	defaultorder="ascending" pagesize="10">
	<display:column property="id" sortable="true" title="Employee ID"
		maxLength="25" />
	<display:column property="name" sortable="true" title="Real Name"
		maxLength="25" />
	<display:column property="emailAddress" sortable="true"
		title="Email Address" maxLength="25" />
	<display:column property="phone" sortable="true" title="Phone"
		maxLength="25" />
	<display:setProperty name="basic.empty.showtable" value="true" />
	<display:setProperty name="paging.banner.group_size" value="10" />
	<display:setProperty name="paging.banner.item_name" value="user" />
	<display:setProperty name="paging.banner.item_names" value="users" />
	<display:setProperty name="paging.banner.onepage" value="<span class="pagelinks">&nbsp;</span>" />
</display:table>
</body>

Running your webapp and navigating to displaytag.html should now display your table like this :
displaytag1

Try sorting your list based on the name of the person. You will notice that only the entries that are on the page in view and sorted, not the entire list. This is not ideal since the entire list should be sorted. A lot of people run into this problem of only one page sorting with displaytag. To make this work you need to add a file with the name displaytag.properties to your classpath. displaytag will automagically pick up settings specified in this file. My displaytag.properties looks something like this :

sort.amount = list
basic.empty.showtable = true
paging.banner.placement = top

The sort.amount tells displaytag to sort the entire list and not just the current page when sorting lists. The basic.empty.showtable settings tells display tag to show a table even if it contains no data. paging.banner.placement tells displaytag to always place the pagination banner on top of the table display.

Remember, it doesn’t matter where your list of users comes from, displaytag picks it up from the session and shows it. You don’t need spring or anything else for displaytag to work. I used spring because I just find it really easy to make examples using it.

Share

No related posts.

  1. Aslam Khatri
    June 28th, 2009 at 10:05
    Reply | Quote | #1

    This article was helpful to me doing pagination and sorting in display tag.Thanks

  2. YSL Prasnath Kumar
    August 7th, 2009 at 14:22
    Reply | Quote | #2

    Hi All,
    Please some one can mail me this code. I need to submit my work and need pagination ASAP. Please help me in sending this full code sample.
    My job depends on this work
    Please send me mail to this :prasanth_2955@hotmail.com

  3. usman
    November 29th, 2009 at 21:53
    Reply | Quote | #3

    Thanks alot and thanks to display tags :)
    very informative article written, so easy to implement.

  4. Aries Satriana
    February 11th, 2010 at 13:48
    Reply | Quote | #5

    Just to inform that you forgot to include property “requestURI” with empty string.
    To be like this

    Rgds

  5. Aries Satriana
    February 11th, 2010 at 13:49
    Reply | Quote | #6

    &ltdisplay:table uid=”user” name=”sessionScope.userList” defaultsort=”1″
    # defaultorder=”ascending” pagesize=”10″ requestURI=”" &gt

    • July 17th, 2011 at 11:45
      Reply | Quote | #7

      Unbelievable how well-written and ifrnomaitve this was.

  6. Aries Satriana
    February 11th, 2010 at 13:49
    Reply | Quote | #8

    <!–

    –>

  7. sumit
    December 12th, 2010 at 15:26
    Reply | Quote | #9

    Hey hi aries it seem you managed to run that example….can you email me the source code please i need it as soon as possible and its very very important for me…….thanks in advacne for that. :) :)

  8. raju
    December 14th, 2010 at 16:25

    Please send this code to me aswell

  9. prawyn
    December 14th, 2010 at 18:58

    Hi, When i use the Display Tag with spring.
    The Sort is not working exactly for Interger, Strings columns.
    The Sorting is happening on the Basis of STRING.(Means The interger sort is not perfect.)
    The Fload Values are are also not getting sorted properly.
    Can you please help in this issue.

    Thanks In advance.
    Your quick response is highly appreciated.

    Prawyn.

  10. prawyn
    December 14th, 2010 at 19:00

    Aries,

    It looks you have some kind of Working code with you.
    Could you please, e mail me the Snippet.
    prn.141@gmail.com

    regards,
    Prawyn.

  11. sridhar
    February 1st, 2011 at 12:52

    hi thanks.
    iam searching for how to dispaly table when no data is found,
    finally i got it
    thanks

    • ummul
      April 7th, 2011 at 10:01

      please send me the code

  12. VJAY
    March 7th, 2011 at 21:46

    How to display the sorting images in a table like up arrow and down arrow images

  13. sreenivas
    April 14th, 2011 at 00:54

    we are facing a problem with Display Tag that is if we sort any column sequence no column also automatically sorting even i put sortable=”false” also. we are generating the sequence number by looping a local variable with the list size. How can we freez the row number from sorting?

  14. Manish
    April 27th, 2011 at 00:14

    Hi,
    I am using the display tag library to display records in a table. My records are being shown in Multiple pages, when I click on the Next link or any page link, it is again going to database to fetch results, but I dont want to make a database call everytime user clicks on the Next Page.
    My code is –

    list

    Also, I am setting the list in Session object using below code in my Action class -
    Object oResult = SummaryDataManager.getInstance().getSummaryReport(
    “MDHANOTI”, priceList, searchType, prodName);

    final ArrayList arrReportData = (ArrayList) (((SummaryResult) oResult).getmObject());
    final String headerID = ((SummaryResult) oResult).getmHeaderId();

    session.removeAttribute(“arrReportData”);
    session.setAttribute(“arrReportData”, arrReportData);
    request.setAttribute(“headerId”, headerID);

    Can someone please help me how can I achieve this.

    Thanks,
    Manish

    • Anand
      September 22nd, 2011 at 17:57

      did you get solution for this problem?

  15. Manish
    April 27th, 2011 at 01:50

    I am sorry, somehow the table tag got messed up. Here is the Tag ….

    I would appreciate your response on this.

    ~ Manish

  16. Manish
    April 27th, 2011 at 01:51

    “”"”‘ “”"”"”

  17. latha
    May 13th, 2011 at 17:23

    this example is good .plz mail me full example.
    i need urgent.

  18. ummul
    May 28th, 2011 at 18:52

    I am getting familiar with displaytag but now i am facing problem as displaytag contains no attibutes of events(displaytag doesn’t support javascript)
    I want to perform deletion on data in display tag when i click that row , how?

  19. Dillibabu
    June 23rd, 2011 at 08:13

    I want to use color to a single column based on retrieved value by display tag. can anyone help on this.

    • Bharat
      July 4th, 2011 at 14:53

      You can use java script by accessing the value from the generated table and apply css on particular table’s cell based on your business logic.

  20. Ashish
    July 11th, 2011 at 15:09

    How we can add hyperlinks to the table, so that while clicking on the any row, the selected row properties can be fetched from the table?

    Please provide suggestions on this…

  21. sikinder
    July 23rd, 2011 at 11:30

    You have to add the HTML link in the decorator class.
    Ex: public class XXXDecorator extends TableDecorator{


    private String studentId;

    public String getStudentId(){
    StuData stuData = (StuData)getCurrentRowObject();
    return "stuData.getStuNo()";
    }
    }

  22. deepanshu
    August 9th, 2011 at 17:33

    please guys,..tell me ,.how can i write this to tag

    <html:hidden value="” property=”hide”/>

    • Krishna
      December 7th, 2011 at 16:21

      You need to first include Stuts tag library in your JSP page, then only you can use this tag

  23. August 10th, 2011 at 19:44

    hi … somebody help me with the code please… i’m using spring 3

    my email is maxesp123@yahoo.com

    best regards.

  24. August 10th, 2011 at 19:45

    hi … somebody help me with the code about pagination in displaytag please… i’m using spring 3

    my email is maxesp123@yahoo.com

    best regards.

  25. senthilnathan
    August 30th, 2011 at 10:55

    whether example shown here is maintained in session or each time database call happens?

  26. Kamal
    September 8th, 2011 at 18:23

    Please I appreciate if someone can send me the source code of this pagination example.
    my email : majidnakit@yahoo.com

    Thanks lot.
    Kamal

  27. guest
    September 12th, 2011 at 18:15

    hi,

    is it possible to define dynamically pagesize, for e.g pagesize=20 but when user click on checkbox show all records, to modify pagesize value?

  28. Akshata
    September 15th, 2011 at 12:28

    Hi,

    My display table showing data on ajax call. If I used your code , when i click on next for pagination it is refreshing whole page. what should I do. I m using Spring MVC pattern.

    Can u please help me?

  29. September 22nd, 2011 at 10:18

    @Akshata, try filtering out displaytag pagination url which startswith “-d”, see here for more details 10 displaytag examples

  30. Rax
    October 25th, 2011 at 01:31

    If we have less than a page display tag shows like

    8 items found, displaying all items.1

    but 1 at the end looks Odd. I got requirement to remove that 1.

    If any body wants to remove that 1 use the below tag and give pagelinks in single coats.

    U may get error by below statement :

    <display:setProperty name="paging.banner.onepage" value=" ” />

    Correct way:
    <display:setProperty name="paging.banner.onepage" value=" ” />

  31. sankar
    October 25th, 2011 at 18:43

    Hi ,

    We r facing an issue in our project the display tag while pagination is appended with some extra values due to which the pagination is not working properly . can u pls let me know how link on the pagination is formed

  32. Krishna
    December 7th, 2011 at 16:24

    Can I have below .css file to get the actual screen and images?

  33. saravan
    December 28th, 2011 at 12:30

    Could u mail me the source code of this plz?????????