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 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.

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. 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 & family", 69, 35)); userList.add(new ForbesData(4, "Lawrence Ellison", 64, 22.5)); userList.add(new ForbesData(5, "Ingvar Kamprad & 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 & 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; } }
Code language: Java (java)
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; } }
Code language: Java (java)
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); } }
Code language: Java (java)

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. Copy following content into appropriate files.

index.jsp

<%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <jsp:forward page="userAction.do"/>
Code language: HTML, XML (xml)

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 > <display:column > <display:column > <display:column > </display:table> </body> </html>
Code language: HTML, XML (xml)

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>
Code language: HTML, XML (xml)

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>
Code language: HTML, XML (xml)

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.

View Comments

  • 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

  • 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?

  • 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.

  • 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

  • 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>
    
    • i need help - i am using struts 1.2 display tag i am having problem with populating the values from ajax response in the table
      thanks

  • 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!

  • 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?

    • 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;
      }

  • 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

    • 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

Share
Published by
Viral Patel
Tags: displaytags displaytags sorting pagination Struts struts displaytag

Recent Posts

  • Java

Java URL Encoder/Decoder Example

Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…

4 years ago
  • General

How to Show Multiple Examples in OpenAPI Spec

Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…

4 years ago
  • General

How to Run Local WordPress using Docker

Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…

4 years ago
  • Java

Create and Validate JWT Token in Java using JJWT

1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…

4 years ago
  • Spring Boot

Spring Boot GraphQL Subscription Realtime API

GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…

4 years ago
  • Spring Boot

Spring Boot DynamoDB Integration Test using Testcontainers

1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…

5 years ago