Showing posts with label Display Tag. Show all posts
Showing posts with label Display Tag. Show all posts

Tuesday, 16 April 2013

if condition in display tag?

Leave a Comment
Use JSTL for if condition in display tag.

Include this library in your jsp page:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
 
<display:column sortable="true" title="Grand Total">
        <c:if test="${data.zone != 'GRAND TOTAL'}">      
            <html:link action="/exceptionScoreCardGrandReport.do?zone=${data.zone}">
                <b>${data.grandTotal}</b>
            </html:link>
        </c:if>
    </display:column>  
Read More...

Friday, 1 February 2013

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

Leave a Comment
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
Read More...

Export to Excel, PDF, CSV and XML using Display tag

Leave a Comment

Using display tag library, we can export the data grid as excel, pdf, csv and xml. In the following example we will see how to dispaly data using display tag and to export as excel, pdf, csv and xml.
The following jar files should be placed in the WEB-INF/lib directory
  • antlr
  • commons-beanutils
  • commons-beanutils-1.7.0
  • commons-collections-3.1
  • commons-digester
  • commons-fileupload-1.0
  • commons-lang-2.3
  • commons-logging
  • commons-validator
  • displaytag-1.2
  • displaytag-export-poi-1.2
  • displaytag-portlet-1.2
  • itext-1.3
  • jakarta-oro
  • log4j-1.2.13
  • struts
itext-1.3.jar file is required incase of exporting to pdf. displaytag-export-poi-1.2.jar is requried to export the file as csv, xml and excel.The following taglib directive should be placed in each JSP page that uses the display tag.

1.<%@ taglib uri="http://displaytag.sf.net" prefix="display" %>
In this example we will display a list of actor's details like name, email Id and the TV show in which they performed. In this example we have a ActorData class which store the actor's details like name, email id and the tv show. The ActorData class has a loadData() method which returns an ArrayList of all the actor details.
The following attributes and methods are present in the ActorData class.

01.public class ActorData
02.{
03.  private String tvShow;
04.  private String userName;
05.  private String emailId;
06.  public ActorData()
07.  {
08. 
09.  }
10. 
11.  public ActorData(String tvShow, String userName, String emailId)
12.  {
13.      this.tvShow = tvShow;
14.      this.userName = userName;
15.      this.emailId = emailId;
16.  }
17.  public ArrayList loadData()
18.  {
19.      ArrayList userList = new ArrayList();
20.      userList.add(new ActorData("The Office","Michael Scott",
21.            "michael.scott@dundermifflin.com"));
22.      userList.add(new ActorData("The Office","Dwight Schrute",
23.            "dwight.schrute@dundermifflin.com"));
24.      userList.add(new ActorData("The Office","Jim Halpert",
25.            "jim.halpert@dundermifflin.com"));
26.      userList.add(new ActorData("The Office","Pam Beesly",
27.            "pam.beesly@dundermifflin.com"));
28.      userList.add(new ActorData("The Office","Andy Bernad",
29.            "andy.bernad@dundermifflin.com"));
30.      userList.add(new ActorData("The Office","Angela Martin",
31.            "angela.martin@dundermifflin.com"));
32.      userList.add(new ActorData("Friends","Rachel Green",
33.            "rachel.green@friends.com"));
34.      userList.add(new ActorData("Friends","Monica Geller",
35.            "monica.geller@friends.com"));
36.      userList.add(new ActorData("Friends","Phoebe Buffay",
37.            "phoebe.buffay@friends.com"));
38.      userList.add(new ActorData("Friends","Joey Tribbiani",
39.            "joey.tribbiani@friends.com"));
40.      userList.add(new ActorData("Friends","Chandler Bing",
41.            "chandler.bing@friends.com"));
42.      userList.add(new ActorData("Friends","Ross Geller",
43.            "ross.geller@friends.com"));
44.      return userList;
45.  }
46.  public String getTvShow() {
47.    return tvShow;
48.  }
49.  public String getUserName() {
50.    return userName;
51.  }
52.  public String getEmailId() {
53.    return emailId;
54.  }
55. 
56.}
In the execute() method of the UserAction class, the loadData() method of ActorData class is called. This method will return an ArrayList of actors, that ArrayList is stored in the actorList attribute of the UserForm class.

1.public ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) throws Exception {
2.    UserForm userForm = (UserForm) form;
3.    ActorData actorData = new ActorData();
4.    userForm.setActorList(actorData.loadData());
5.    return mapping.findForward(SUCCESS);
6.}
Now we will display all the actor data present in the actorList in the jsp page using dispalytag.

1.<display:table id="data" name="sessionScope.UserForm.actorList" requestURI="/userAction.do" pagesize="10" >
2.<display:column property="tvShow" title="TV Show" sortable="true" media="html" group="1" />
3.<display:column property="userName" title="User Name" sortable="true"/>
4.<display:column property="emailId" title="Email Id" sortable="true"/>
5.</display:table>

The export attribute of the table tag should be set to true, inorder to export the data grid. After setting the value the data grid can be exported to excel, csv and xml. If you want to export to pdf then the "export.pdf" property to true.

1.<display:setProperty name="export.pdf" value="true" />
By default the name of the export file will be the name of the jsp page. You can change the name of the pdf file by setting the "export.pdf.filename" property value to the desired file name. In the similar way you can change the name of the excel file by setting "export.excel.filename" property to a desired file name.

1.<display:setProperty name="export.pdf.filename" value="ActorDetails.pdf"/>
2.<display:setProperty name="export.excel.filename" value="ActorDetails.xls"/>
The name attribute of the table tag hold the name of the list in the form. The id value specifies an instance name for the ArrayList. The pagesize attribute holds the number of records to be displayed in each page.
The property attribute of the column tag hold the value of the property to be displayed in this each column. The value of the property can be any one of the property of the ActorData class. The ActorData class should have a getter method for that corresponding property. For instance if the property name is tvShow then their should be a corresponding getTvShow() method in the ActorData class.
If the sortable attribute of the column tag is set to "true" then that column will be sortable.
The group attribute of the column tag is set to "1" , which means each unique data will be displayed only once and will not be repeated for the subsequent times.
The following image shows the first page of the data grid. Since the pagesize is set to ten, ten records are displayed in the first page.

On clicking the Excel link the user will be prompted to open or save the file.

On clicking open the data grid will be displayed in Excel format.

The media property of the column tag is used to specify in which media that column should be shown. If the media is set to "html" then only in the jsp page that particular column will be displayed. If the media is set to "html, excel" then that particular column will be displayed in jsp page as well as in excel.

1.<display:column property="tvShow" title="TV Show" sortable="true" media="html" group="1" />

On clicking the PDF link the user will be prompted to open or save the file.
On clicking open the data grid will be displayed in PDF format.

On clicking the CSV link the data grid will be displayed in the csv format.

On clicking the XML link the data grid will be displayed in the xml format.

You can download the source code of the displaytag export to excel example by clicking on the Download link below.

Source + Lib: Download
Read More...