Struts displaytag tutorial: Sort / Pagination data using displaytag in Struts

      

Struts display tag library is an open source suite of custom tags that provide high-level web presentation patterns which will work in an MVC model. The library provides a significant amount of functionality while still being easy to use. Displaytag can handle column display, sorting, paging, cropping, grouping, exporting, smart linking and decoration of a table in a customizable XHTML style.

In the following example we will see how to dispaly data using display tag and to do pagination and sorting. We will use Eclipse as an IDE for our example.

Step 1: Create Eclipse dynamic web project and copy JAR files

Start Eclipse and goto File -> New -> Project -> Dynamic Web Project
struts dynamic web project

Following is the list of required JAR files to be added in Java Class Path of your project. Download displaytag JAR files from http://displaytag.sourceforge.net/1.2/download.html.

displaytag-jar-file-list

Step 2: Create Action, Form and Bean class

Once the project is created, create 3 java files ForbesData, UserAction and UserForm in package net.viralpatel.struts.displaytag.
struts-displaytag-new-java

Copy following content into ForbesData.java file.

package net.viralpatel.struts.displaytag;

import java.util.ArrayList;

public class ForbesData {
	private int rank;
	private String name;
	private int age;
	private double netWorth;

	public ForbesData() {

	}

	public ForbesData(int rank, String name, int age, double netWorth) {
		this.rank = rank;
		this.name = name;
		this.age = age;
		this.netWorth = netWorth;
	}
	public ArrayList<ForbesData> loadData() {
		ArrayList<ForbesData> userList = new ArrayList<ForbesData>();
		userList.add(new ForbesData(1, "William Gates III", 53, 40.0));
		userList.add(new ForbesData(2, "Warren Buffett", 78, 37));
		userList.add(new ForbesData(3, "Carlos Slim Helu &amp; family", 69, 35));
		userList.add(new ForbesData(4, "Lawrence Ellison", 64, 22.5));
		userList.add(new ForbesData(5, "Ingvar Kamprad &amp; family", 83, 22));
		userList.add(new ForbesData(6, "Karl Albrecht", 89, 21.5));
		userList.add(new ForbesData(7, "Mukesh Ambani", 51, 19.5));
		userList.add(new ForbesData(8, "Lakshmi Mittal", 58, 19.3));
		userList.add(new ForbesData(9, "Theo Albrecht", 87, 18.8));
		userList.add(new ForbesData(10, "Amancio Ortega", 73, 18.3));
		userList.add(new ForbesData(11, "Jim Walton", 61, 17.8));
		userList.add(new ForbesData(12, "Alice Walton", 59, 17.6));
		userList.add(new ForbesData(12, "Christy Walton &amp; family", 54, 17.6));
		userList.add(new ForbesData(12, "S Robson Walton", 65, 17.6));
		userList.add(new ForbesData(15, "Bernard Arnault", 60, 16.5));
		userList.add(new ForbesData(16, "Li Ka-shing", 80, 16.2));
		userList.add(new ForbesData(17, "Michael Bloomberg", 67, 16));
		userList.add(new ForbesData(18, "Stefan Persson", 61, 14.5));
		userList.add(new ForbesData(19, "Charles Koch", 73, 14));
		userList.add(new ForbesData(19, "David Koch", 68, 14));
		userList.add(new ForbesData(21, "Liliane Bettencourt", 86, 13.4));
		userList.add(new ForbesData(22, "Prince Alwaleed Bin Talal Alsaud", 54, 13.3));
		return userList;
	}
	public int getRank() {
		return rank;
	}
	public void setRank(int rank) {
		this.rank = rank;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public double getNetWorth() {
		return netWorth;
	}
	public void setNetWorth(double netWorth) {
		this.netWorth = netWorth;
	}
}

Copy following content into UserForm.java

package net.viralpatel.struts.displaytag;

import java.util.ArrayList;

public class UserForm extends org.apache.struts.action.ActionForm {

	private ArrayList<ForbesData> forbesList;

	public ArrayList<ForbesData> getForbesList() {
		return forbesList;
	}

	public void setForbesList(ArrayList<ForbesData> forbesList) {
		this.forbesList = forbesList;
	}
}

Copy following content into UserAction.java

package net.viralpatel.struts.displaytag;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class UserAction extends Action {

    private final static String SUCCESS = "success";

	public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        UserForm userForm = (UserForm) form;
        ForbesData actorData = new ForbesData();
        userForm.setForbesList(actorData.loadData());
        return mapping.findForward(SUCCESS);
    }

}

Step 3: Create JSPs, struts-config.xml and web.xml

Create index.jsp and user.jsp in WebContent folder and struts-config.xml and web.xml in WebContent/WEB-INF folder.
struts-displaytag-web-xml-jsp

Copy following content into appropriate files.

index.jsp

<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>

<jsp:forward page="userAction.do"/>

user.jsp

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="http://displaytag.sf.net" prefix="display" %>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>The World's Billionaires 2009</title>
        <link href="css/style.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
    <h2>The World's Billionaires 2009 - Forbes List</h2>
        <display:table export="true"  id="data"
        			name="sessionScope.UserForm.forbesList"
        			requestURI="/userAction.do" pagesize="10" >
            <display:column property="rank" title="Rank" sortable="true"   />
            <display:column property="name" title="Name" sortable="true"  />
            <display:column property="age" title="Age" sortable="true"  />
            <display:column property="netWorth" title="Net worth ($BIL)"
            		sortable="true"  />
        </display:table>
    </body>
</html>

struts-config.xml

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts-config PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
          "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">

<struts-config>
    <form-beans>
        <form-bean name="UserForm"
        	type="net.viralpatel.struts.displaytag.UserForm"/>
    </form-beans>

    <global-exceptions>

    </global-exceptions>

    <global-forwards>
        <forward name="welcome"  path="/Welcome.do"/>
    </global-forwards>

    <action-mappings>
        <action input="/" name="UserForm" path="/userAction"
        	scope="session" type="net.viralpatel.struts.displaytag.UserAction">
            <forward name="success" path="/user.jsp" />
        </action>
        <action path="/Welcome" forward="/welcomeStruts.jsp"/>
    </action-mappings>

    <message-resources parameter="com/vaannila/ApplicationResource"/>

</struts-config>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	<servlet>
		<servlet-name>action</servlet-name>
		<servlet-class>
			org.apache.struts.action.ActionServlet
		</servlet-class>
		<init-param>
			<param-name>config</param-name>
			<param-value>/WEB-INF/struts-config.xml</param-value>
		</init-param>
		<init-param>
			<param-name>debug</param-name>
			<param-value>2</param-value>
		</init-param>
		<init-param>
			<param-name>detail</param-name>
			<param-value>2</param-value>
		</init-param>
		<load-on-startup>2</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>action</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>
	<session-config>
		<session-timeout>30</session-timeout>
	</session-config>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

Step 4: Execute the project

We are done with the project. Now execute the project in eclipse or create a WAR file and run it in Tomcat.

struts-displaytag-example


Facebook  Twitter      Stumbleupon  Delicious
  

57 Comments on “Struts displaytag tutorial: Sort / Pagination data using displaytag in Struts”

  • Kiran wrote on 15 June, 2009, 12:27

    Nice one dude

  • Sateesh wrote on 17 July, 2009, 17:28

    Application is very helpful and the way what you people explained really good.
    At a single shot we can develop the application like making coffee.
    Thanks dudes… keep maintain these type of application .
    Sateesh

  • Surabhi wrote on 22 July, 2009, 10:18

    Hi Viral,
    I am encountering a problem while running it. When I add the taglib. it shows me an error at the tag where the display tag is used. I am not able to view the output. How can I correct it?

  • Viral Patel wrote on 22 July, 2009, 20:20

    Hi Surabhi, I think you getting the error may be because required JAR files are missing or not properly added. Check the JAR file for Struts display tag and also check the version.

  • ujjawal wrote on 28 July, 2009, 13:42

    viral sir
    how u display in jsp ?22 items found displying 1 to 10 ..where is jsp code ???pls let me know asap

    regards
    ujjawal

  • Vadi wrote on 11 August, 2009, 0:32

    with Ajax:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
    <%@taglib uri="http://displaytag.sf.net" prefix="display" %>
    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <title>The World\'s Billionaires 2009</title>
            <link rel="stylesheet" href="css/displaytag.css">
    		<style media="all" type="text/css">
    		@import "css/maven-base.css";
    		@import "css/maven-theme.css";
    		@import "css/site.css";
    		@import "css/screen.css";
    		@import "css/displaytag.css";
    		</style>
    		<script language=\'javascript\' src="js/jquery.js" type="text/javascript"></script>
    		<script src="js/displayTagAjax.js"></script>
        </head>
        <body>
        <div id="ajxDspId">
        <h2>The World\'s Billionaires 2009 - Forbes List</h2>
            <display:table export="true"  id="data"
            			name="sessionScope.UserForm.forbesList"
            			requestURI="/userAction.do" pagesize="10" >
                <display:column property="rank" title="Rank" sortable="true"   />
                <display:column property="name" title="Name" sortable="true"  />
                <display:column property="age" title="Age" sortable="true"  />
                <display:column property="netWorth" title="Net worth ($BIL)"
                		sortable="true"  />
            </display:table>
        </div>
        </body>
    </html>
    
  • Jake wrote on 15 August, 2009, 15:51

    Hi Viral, this looks like an excellent tutorial! Unfortunately I’m using Struts 2. Do you have any advice on how I’d implement this in Struts2?

    Thanks!

  • Viral Patel wrote on 16 August, 2009, 19:24

    @Jake, Thanks for the comment.. I will try to write the same article for Struts 2 :)

  • yosefus wrote on 6 October, 2009, 21:55

    I have a related question: I keep seeing these HTML/CODE/PHP snippets that are shown in a similar way, with line numbers, odd and even line highlighting etc. My question is: what editor works that way? i’d like to use it also and produce screenshots like that.

    can someone reply to yosefus11@gmail.com?

  • Viral Patel wrote on 6 October, 2009, 22:40

    Hi Yosefus,
    For adding style sheet like odd even colors to the displaytable, you have to add following CSS classes in the CSS file that you include in JSP.

    odd- assigned to the tr tag of all odd numbered data rows
    even- assigned to the tr tag of all even numbered data rows
    sorted- assigned to the th tag of the sorted column
    order1- assigned to the th tag of the sorted column if sort order is ascending
    order2- assigned to the th tag of the sorted column if sort order is descending
    sortable- assigned to the th tag of a sortable column

    Thus your CSS file may have entry like:

    .odd {
    background-color: white;
    }
    .even {
    background-color: #FFEE88;
    }

  • smita wrote on 23 October, 2009, 10:56

    I am getting the error when I add the taglib for displaytag in user.jsp

    JSP Page

    I am getting compiletime error as NoClassDefFoundError.

    Please help me.
    I am using struts-1.2.9.jar

  • ramchandra wrote on 23 October, 2009, 12:25

    das

  • Viral Patel wrote on 23 October, 2009, 12:50

    Hi Smita,
    For using Displaytag library, you need to include its jar files in classpath. Check if your classpath has these jars:

    displaytag-1.2.jar
    displaytag-export-poi-1.2.jar
    displaytag-portlet-1.2.jar

  • smita wrote on 24 October, 2009, 13:50

    Hi,
    I want to add edit/delete link in display:table tag.When i click on the link for particular row (e.g. data for row having name field as ‘smits’ should be displayed on the form) the data should be displayed in text so that i can edit it.
    Can you plese give me some sample code for edit and delete row from display:table also from database.

    Please help me out

  • harshal wrote on 24 October, 2009, 17:17

    Hi,
    Can you please tell me how to use edit and delete link in tag using struts?
    Please tell me Asap.

    Thanks,
    Harshal

  • harshal wrote on 24 October, 2009, 17:19

    Sorry I forgot to mension using display:table tag in struts.

    Thanks,
    Harshal

  • Bijoy Baral wrote on 24 November, 2009, 17:32

    Nice Work dude

  • mehar wrote on 2 December, 2009, 10:54

    Hi,

    I get an warning when i use the above jsp page .

    This works out but gives another problem tag lib not found .

    I added all the tag libraries in the class path

  • mehar wrote on 2 December, 2009, 10:55

    i use this in the jsp page

  • Majid wrote on 2 December, 2009, 22:02

    I got this error :

    org.apache.jasper.JasperException: The absolute uri: http://displaytag.sf.net cannot be resolved in either web.xml or the jar files deployed with this application

  • Viral Patel wrote on 3 December, 2009, 16:09

    @Majid – Please check the version of displaytag jar you using. Include the correct version. I have used version 1.2 of DisplayTag. You may want to check the correct url in your jar file.

  • ashish wrote on 29 December, 2009, 17:40

    Hi Viral,
    Appriciate your help to convert pagination style in
    { First | Prev | 1 2 3 4 | Next | Last }
    or
    { First | Prev | (page 1, Item 1-10 ) in select/drop down | Next | Last }.
    Simply wann to remove brackets i.e.
    [First/Prev] 1, 2, 3, 4 [Next/Last]

  • Viral Patel wrote on 29 December, 2009, 19:20

    @ashish: You can configure the pagination links by changing the property in displaytag.properties file. For overriding the default properties, you need to create a file called displaytag.properties and place it in classpath. And change the property paging.banner.full which by default is:

     [<a href="{1}" rel="nofollow">First</a>/ <a href="{2}" rel="nofollow">Prev</a>]
    {0} [
    <a href="{3}" rel="nofollow">Next</a>/ <a href="{4}" rel="nofollow">Last </a>]
    

    and modify the default value and change it into:

     <a href="{1}" rel="nofollow">First</a> | <a href="{2}" rel="nofollow">Prev</a> |
     {0} |
     <a href="{3}" rel="nofollow">Next</a> | <a href="{4}" rel="nofollow">Last </a>
    

    Check the document at http://displaytag.sourceforge.net/10/configuration.html for more details.

    Hope this will resolve the issue.

  • amit wrote on 12 January, 2010, 12:43

    hii viral
    i have included the jar files mentioned but still i am getting this error after deploying it on netbeans
    it says:
    javax.servlet.ServletException: java.lang.NoClassDefFoundError: org/apache/commons/lang/UnhandledException

    java.lang.NoClassDefFoundError: org/apache/commons/lang/UnhandledException

    Pls help me out
    thanks

  • Viral Patel wrote on 12 January, 2010, 15:23

    @Amit – Check if you have included commons-lang.jar file in your classpath.

  • amit wrote on 12 January, 2010, 15:39

    Thanks viral…
    But i have no idea about the commons-lang.jar…

    I have just added the 3 jar files that you have talked about previously related to displaytags.
    Could you throw some more light about the commons-lang.jar a little more
    Thanks:)

  • amit wrote on 12 January, 2010, 15:46

    Also i have not added the previous jar files to the path instead just added them to netbeans library. Is the error because of the same?

    Thanks:)

  • Viral Patel wrote on 12 January, 2010, 18:15

    Amit – If you check the second screen shot in Step-1, you will see the list of JAR files required for this project. Include all these JARs in your project to work with display tag.

  • cesar wrote on 16 January, 2010, 23:23

    javax.servlet.ServletException: java.lang.NoClassDefFoundError: org/apache/commons/lang/UnhandledException

    i add the library common-lang y show that error

  • Mohan wrote on 21 January, 2010, 15:11

    How to change the pager style ? want to enter the page no and click go?.
    thnks

  • Zubin wrote on 6 February, 2010, 17:51

    hey….thanks for the code….How to add Edit Button and check box at each row ??? can u plz give code in struts 2 with the example???

  • Sibashis wrote on 16 February, 2010, 14:19

    Hi,
    Nice job, but in this tutorial u r get an predefined items in the ArrayList object and then u store it session scope(if I’m not wrong)………that’s mean when we fetch some huge data from database dynamically then the session will be heavy…………….can u demonstrate it into request scope with every time when user click the next button every time an sql query fire (with just change the value of ‘LIMIT ‘ dynamically) and give me the next page

  • Jee wrote on 25 February, 2010, 19:12

    Excellent one… is useful verymuch

  • Ravikumar wrote on 3 March, 2010, 8:17

    Nice Job; error free navigated example;

  • Helen Neely wrote on 4 March, 2010, 15:25

    Awesome tutorial, thanks for sharing this piece of code. I think we need more of this lovely example on how to implement pagination and struts.

    Great job.

  • yedukondalu wrote on 5 March, 2010, 7:44

    good job dude

  • zee wrote on 14 March, 2010, 0:36

    the information is really helpful but can you tell me how i can perform pagination in struts2…Since there is no Action mapping in used in Struts2 …i have no clue how i can perform this.

  • souna wrote on 1 April, 2010, 16:41

    Thank’s a lot!
    This was very helpful for me!
    Great job

  • NIHAR RANJAN MISHRA wrote on 2 April, 2010, 17:29

    hi amit….just want to know, how to set display tag value in dropdown, or text field etc.

  • Prabahar wrote on 23 April, 2010, 14:38

    Hi Viral, I am using struts2 to develop portlets to deploy in IBM portal server 6.1 using RAD 7.5. I am using display tags to present list datatypes in JSP. But i can able to display table when the data is in request scope. I want to get values from session and display in table. DT is not reading session scope objects. Can you please help me out in finding the solution?

  • ramkee2k wrote on 28 April, 2010, 13:06

    1.when i export excel file, title of the column in the excel should need background colour cells excel sheet.

    2. i don’t to display no item found when table is empty.

    can any help me sloving this issue.

    thank you

  • ramkee2k wrote on 4 May, 2010, 23:02

    I AM DOWNLOAD THE EXCEL SHEET I AM GET THE BELOW EXCEPTION. CAN ANY ONE FACED THIS KIND OF ISSUE………

    javax.servlet.ServletException: org/apache/poi/hssf/usermodel/HSSFWorkbook

    THANK YOU.

  • Dennis Labajo wrote on 10 May, 2010, 21:00

    Does pagination only extract records (for exmaple, from a database) during navigation time when the user is clicking on the forward / backward / first / last buttons or does displaytag need to load the entire list of data (in memory) once the UI page is rendered?

    If I have a search screen and the user mistakingly created a search filter that returns thousands of records, I’d hate to load that amount of data in memory. What I would like to do is display only a small subset of data returned from the search result and extracts the next subset depending on the user navigation/pagination. Is this how displaytag works?

  • Meera wrote on 12 May, 2010, 19:00

    Viral: Is it possible to add an image, a link and 2 different types of text to a single column using
    display tags? I really appreciate your help in this. Thanks.

    So I want to display an 4 properties on an Object in one column rather than a single property as shown in the example given, Thanks

    Meera

  • Manoj Nikam wrote on 7 June, 2010, 16:38

    Hi,
    This stuff is really helpful for display tag usage.
    But I have some different scenario for the display tag which is as below.
    I am using an AJAX to call the internal .jsp pages inside one template .jsp page,
    And I am using display tag inside the inner page for displaying list and using export functionality of display tag.
    But my problem with display tag is I am not able to use sort functionality due to AJAX.

    Can anybody tell me how I should call JavaScript function from display tag for sorting functionality?

    Thanks in advance,
    Manoj Nikam.

  • kumar wrote on 8 June, 2010, 17:05

    hi friends…. can you use dispalytag in struts2 version. if it’s possible means..reply

  • Steven wrote on 10 June, 2010, 22:24

    Kumar,
    I just got this working with Struts 2 myself. So it is possible. The main differences are on the user.jsp page and for me my Contacts class.

    I actually started with the tutorial Viral posted on using Hibernate with Struts 2:
    http://viralpatel.net/blogs/2010/01/tutorial-struts2-hibernate-example-eclipse.html

    I added the jar files listed here that were not already present, then

    I had to change the Contacts class so it was Comparable (required for sorting)

    public class Contact implements Serializable, Comparable { …

    Then instead of name=”sessionScope.UserForm.forbesList” I used the list of contacts I pulled from a database using hibernate listContacts. This is made available from the ContactAction which is specified in my struts.xml file when I call this .jsp file. Then I list an action in the requestURI=”" I just used index since that was my action that called this page.

    That is all I remember changing here. Hope this helps.

    Steven

  • Steven wrote on 10 June, 2010, 22:27

    Oh…and i changed the properties on the display:column tags to match my contacts class. But i suppose you guessed that already.

    Steven

  • Sirisha wrote on 2 July, 2010, 14:32

    Hi Viral,

    Firstly i thank u for the work u’ve done and its very useful for the learners and beginners like me. I just need one clarification from u. are the jar files which u’ve mentioned are suffficient to run this program or anything else to be added. I’m using struts frame work, and i couldn’t get the data it’s showing that nothing found to be displayed. Can u tell y exactly this problem is coming

  • Archie wrote on 6 July, 2010, 15:53

    Can you explain how to pass parameters through the href tag of Displaytag?

  • Arpan wrote on 20 July, 2010, 11:58

    Thanking you sir!

  • Amit Thakur wrote on 21 July, 2010, 12:10

    hi viral i want to display data horizontally like here data is coming in form of table like

    SNO. Question Solution Version

    I want to display data like :

    SNO.
    Qusetion :
    Solution :
    Version :

    How can i achieve this output through display tag.
    my mail id : amitthakur10832@gmail.com

  • Amit Thakur wrote on 21 July, 2010, 13:31

    Viral i want to display data like in this form with help of displaytag :

    Rank : 1
    Name : Bill gats
    Age : 58

    Rank : 2
    Name : Waren Buffet
    Age : 68

  • nithya wrote on 28 July, 2010, 12:29

    Good, Keep writing more

    Nithya
    http://www.liveyourdreamsindia.com

  • Jordi wrote on 7 August, 2010, 18:35

    This tutorial helped me a lot, now my aplication works fine wit displaytag.
    Good job.

  • DeepakLal wrote on 19 August, 2010, 23:04

    Hi canone copy and paste the working source code so that it can be used for further re-usability.i need a consolidate version./…please help

  • Mamata wrote on 26 August, 2010, 16:34

    Hi ,can any body please let me know how to pass one reference variable using display tag when calling javascript method,Here my code is like:-

    ——–>Here if i’ll do like this i used to get always 1st row Value.Even tried removing ” mark also but that time my javascript method not able to call.Somebody could help me to work out.

Write a Comment

Gravatars are small images that can show your personality. You can get your gravatar for free today!

Copyright © 2010 ViralPatel.net. All rights reserved.