Thursday, November 30, 2006

Pagination with DisplayTag

Displaytag is an opensource tag library that can be used to display tables on JSPs. Apart from being able to display tables, the displaytag library also has support for JSR-168 compliant portals through the "Display portal compatibility library", and also supports exporting tables to Excel through the "Excel export module". The following example demonstrates the use of DisplayTag to display a long list as a multi-page table. For this example, I used the default EMP table from the sample database which will be built at during Oracle installation. This example uses Oracle 10g R2, Java 5, Tomcat 5.5 and Hibernate 3.2.
Skip to Sample Code
To run the example, follow these steps:
  1. Download Displaytags from here, and include the displaytag-1.1.jar file in your classpath.
  2. Download the latest version of hibernate from hibernate.org, and include all the required jars in your classpath.
  3. Create the pagingEmp.jsp page as shown below
    <jsp:root version="1.2" xmlns:jsp="http://java.sun.com/JSP/Page"
    xmlns:display="urn:jsptld:http://displaytag.sf.net">
    <jsp:directive.page contentType="text/html; charset=UTF-8" />
    <link rel="stylesheet" type="text/css" href="css/screen.css" />
    <jsp:scriptlet>
    session.setAttribute( "EmpList", data.DAO.getData());
    </jsp:scriptlet>
    <h2 align="center">Emp Table with Display tag</h2>
    <display:table name="sessionScope.EmpList" pagesize="4">
    <display:column property="empId" title="ID" />
    <display:column property="empName" title="Name" />
    <display:column property="empJob" title="Job" />
    <display:column property="empSal" title="Salary" />
    </display:table>
    </jsp:root>
    pagingEmp.jsp
  4. Create the Employee class, which is the bean that will hold the Employee data as shown below:
    public class Employee {
    public long empId;
    public String empName;
    public String empJob;
    public long empSal;
    public long getEmpId() {
    return empId;
    }
    public void setEmpId(long empId) {
    this.empId = empId;
    }
    public String getEmpJob() {
    return empJob;
    }
    public void setEmpJob(String empJob) {
    this.empJob = empJob;
    }
    public String getEmpName() {
    return empName;
    }
    public void setEmpName(String empName) {
    this.empName = empName;
    }
    public long getEmpSal() {
    return empSal;
    }
    public void setEmpSal(long empSal) {
    this.empSal = empSal;
    }
    }
    Employee.java
  5. Define the styles for displaying the table. Displaytag renders the tables as simple HTML tables, with the standart tr,td,th and table tags. The css file is shown below
    td {
    font-size: 0.65em;
    font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
    font-size: 11px;
    }
    th {
    font-size: 0.85em;
    border-top: 2px solid #ddd;
    border-right: 2px solid #ddd;
    border-left: 2px solid #666;
    border-bottom: 2px solid #666;
    }
    table {
    border: 1px dotted #666;
    width: 80%;
    margin: 20px 0 20px 0;
    }
    th,td {
    margin: 0;
    padding: 0;
    text-align: left;
    vertical-align: top;
    background-repeat: no-repeat;
    list-style-type: none;
    }
    thead tr {
    background-color: #bbb;
    }
    tr.odd {
    background-color: #fff;
    }
    tr.even {
    background-color: #ddd;
    }
    screen.css
  6. Configure Hibernate for accessing database
    1. Create the Employee.hbm.xml file to map the Employee bean with the database table as shown below
      <?xml version="1.0"?>
      <!DOCTYPE hibernate-mapping PUBLIC
      "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
      "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
      <hibernate-mapping>
      <class name="beans.Employee" table="Emp">
      <id name="empId" column="EMPNO" type="long">
      <generator class="native"/>
      </id>
      <property name="empName" column="ENAME" />
      <property name="empJob" column="JOB" />
      <property name="empSal" column="SAL" type="long"/>
      </class>
      </hibernate-mapping>
      Employee.hbm.xml

      This file is placed in the same directory as the Employee.java class.
    2. Create the Hibernate Configuration file hibernate.cfg.xml in the root directory of the classes.
      <?xml version='1.0' encoding='utf-8'?>
      <!DOCTYPE hibernate-configuration PUBLIC
      "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
      "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
      <hibernate-configuration>
      <session-factory>
      <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
      <property name="connection.url">jdbc:oracle:thin:@localhost:1521/orcl</property>
      <property name="connection.username">scott</property>
      <property name="connection.password">tiger</property>
      <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
      <mapping resource="beans/Employee.hbm.xml"/>
      <property name="hibernate.current_session_context_class">thread</property>
      </session-factory>
      </hibernate-configuration>
      hibernate.cfg.xml
  7. Create a class for Data access as shown below
    public class DAO {
    public static List getData() {
    SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
    Session session = sessionFactory.getCurrentSession();
    List result = null;
    try {
    session.beginTransaction();
    result = session.createQuery("from Employee").list();
    session.getTransaction().commit();
    } catch (Exception e) {
    e.printStackTrace();
    }
    return result;
    }
    }
    DAO.java
Running this example on tomcat shows the Emp table data in a table with 4 records per page, as set in the pagesize attribute of the display:table tag.

31 comments:

  1. Hi
    i am using display tag pagination & its working fine..
    But i want to retrieve only that much of rows which i mention in pagesize Attribute of display tag .

    In actual practice i am displaying 15 records per page but each time when i click on to next link ,the query gets fired & the size of resulset of this query is 2000 records.
    Out of these 2000 records display tag properly displaying next 15 records..
    But the problem is - i don't want to retrieve 2000 rec. for each time
    when i click on next link.In my DAO class itself i want to retrieve that much of records only which i mentioned in pagesize attribute

    ReplyDelete
  2. You will have the problem if you directly used the example I showed above (I did not consider any optimizations for the example). In order to avoid this problem you will have to replace the following line
    session.setAttribute( "EmpList", data.DAO.getData());

    with the following

    if(session.getAttribute("EmpList") == null) {
    session.setAttribute( "EmpList", data.DAO.getData());
    }

    Note that it is not a good idea to put this Data access code in the JSP either.

    ReplyDelete
  3. Hi Abhi ,
    Thanks for the reply.
    What you suggested is very good. But we are using MVC architecture in our company & we can't call the DAO function from JSP directly. So in Action Class i will check this condition, then it will be fine..
    But the disadvantage as u pointed out is that its not a good idea to store such a big object ( in my case object size is more than 65000 ) So it will be good if we fetch records in sets from database itself..
    For this reason i tried by parameterized query ,but i am using the MS SQL 2000 Server DB ,so on this DB am unable to find any parameterized query for pagination support (there are stored procedure but i want simple query). So i manage to implement the query like:-

    SELECT TOP 15 DeviceID
    FROM Device_PlaceHolder
    WHERE (DeviceID NOT IN
    (SELECT TOP 15 deviceid
    FROM device_placeholder))
    where value of top clause will be parameter
    Now,the only problem is how can i call these query on display tag,s next & previous link
    OR Do you have any other idea to implement my this requirement (with display tag or without it)?
    I also tried with extremecomponents but i don't know how can i call my query with it on MS SQL 2000
    According to me in extremecomponents there is LimitFactory class but its logic works on limit clause of mySql only)
    So is there any server side pagination support in display tag ?

    Please guide me ...i am waiting for reply
    Thanks once again...

    ReplyDelete
  4. You can use the setFirstResult(int resultNum) and setMaxResults(int pageSize) methods in Hibernate as I showed in Paging in JSP with Hibernate. You would get the total results using an additional query.

    OR
    You can use some clever querying as shown in this article.

    Both solutions do not use Displaytag. I should also say that I am not much acquainted with using SQL Server from Java, it may have additional features or limitations.

    ReplyDelete
  5. hi,

    can i mix ur solution of paging in JSP with hibernate and display tag.

    Can u give some idea about this how to do this?

    ReplyDelete
  6. hi abhi,
    Thnkx for replying...but this link goes to "paging-in-jsp-with-hibernate" here display tag is not used.

    ReplyDelete
  7. Hello Abhi,
    Do you have an example of retrieving data using struts action class and displaying it using Displaytag libraries

    ReplyDelete
  8. Hi abhi,
    Using display tag ,we just pass the pageSize hardcoded but what we want is user to specify the pageSize at run time. How can we do this?? Please help.
    Waiting for your reply.
    Thanks in advance.

    ReplyDelete
  9. Hi There,

    I really like your examples about pagining with hibernate and the displaytag. I've been looking at this for a while and the only problem I can see is how to get the page number from the request when the user clicks the page number on the displayTag google page link.

    It seems the displayTag gives the table some random id, e.g. d-12345678-p I can't realy see a way of getting the value off the request or giving the table an id.

    ReplyDelete
  10. Hi ,
    Is there any way to create dynamic picklist in crystal reportsXI.I m able to do it on crystal report thick client but not able to do it in eclipse.
    Please help
    Thanks

    ReplyDelete
  11. Hi Abhi,

    I have a challenging question for you.

    Is there is a possibility to diplay the table vertically instead of horizontally using displaytag(if not an HTML way) i.e I would like the table as

    col1 a1 b1 c1

    col2 a2 b2 c2

    col3 a3 b3 c3

    instead of the regular display way

    col1 col2 col3
    a1 a2 a3
    b1 b2 b3
    c1 c2 c3

    Thanks,
    vb

    ReplyDelete
  12. Hi abhi...
    I am using JSF. In my JSF pages
    i am using dataTable..
    If i want to use the display tag what i have to .

    ReplyDelete
  13. Hi Abhi,
    Can you just guide me how to do the paging stuff in Struts2?

    ReplyDelete
  14. hi can u tell me how to genrate column at runtime not predifne
    that columns

    ReplyDelete
  15. Hi, Abhi

    I have problems linking displaytag with action/form/struts-config.xlm.

    This is what I have:
    MenuAction
    - initialize the arraylist “messageList”
    - servletRequest.getSession().setAttribute("messageList", messages.getMessageList());
    - forwards = “Message.jsp”

    Message.jsp
    *display:table name="sessionScope.messageList" class="dataTable" pagesize="16" cellspacing="0"*
    *display:column property="serviceId"/*
    *display:column property="incomingDate"/*
    *display:column property="ani"/*
    *display:column property="dni"/*
    *display:column property="message"/*
    *display:column property="deliveryDate"/*
    */display:table*

    When I click next on paging-menu I’ve got
    java.lang.NullPointerException
    at org.apache.jsp.WEBSITE.Messages_jsp._jspService

    I read on other post to set displaytags’ attribute requestURI=”” but it doesn’t work either. I know I have to configure something on struts-config.xlm and create an action class associated with this.

    I’ll appreciate any help you can give me on this.

    Best regards,

    Francisco

    PD. I had to put replace < for * in order to be able to summit my question

    ReplyDelete
  16. oi,

    eu gostaria de saber como que eu poderia fazer 1 paginação com o hibernate(pagination with hibernate)i can´t...and i want to take some code...did you have some code on style??

    please..

    *i don´t speak or read
    English very good!!
    i just know some things!!sorry

    ReplyDelete
  17. I would like to know how I can make a layout with hibernate, jsp, struts for browsing some suppliers and accounts payable of the suppliers themselves ...

    if you have some codes to send me this e-mail (hiteounico@hotmail.com)?

    and another thing ... I am Brazilian! but something I translate for the Portuguese

    ReplyDelete
  18. Thank you for this article.
    I need paging with manual by query directly with hibernate. Such as receive pagaing or sorting parameter and calculate it with hibernate.
    Please help me. Thank you very much. Response resovle to my e-mail at thawap@hotmail.com

    ReplyDelete
  19. Abhi,

    Its really nice code samples,it worked for me.
    Now I use display tag for all my applications, its a cool feature.

    Still I need one help,
    If I have multi byte chars on my display tag table,its not coming as it is during export to excel option.

    Could give me some suggestion, how to get that.

    Viki

    ReplyDelete
  20. Hi Abhi,

    The example you gave abt Pagination and Sorting using display tag is simple marvelous. After seeing ur example i decided to use Display tag in my current proj. I have Struts2.0 with Spring and hibernate. I have a requirement where in a table is displayed with user name , email id , date, city(eg delhi, bombay, hyderbad, banglore). I also have a dropdown selection on top of the table and that dropdown contains the cities too(delhi, bombay, hyderbad, banglore). If I select a value, say "delhi" in the dropdown………. Then the table shld display all the values with city as delhi. Can you plz plz and plz help me out with this.
    Thanks in advance.
    Regards,
    Anil

    ReplyDelete
  21. Hi, we are using displaytag for the pagination. The issue we are facing is when the result found it shows the no of records found as 26, and we have given limitation to display only 15 per page. When i try to click on next/last option available it shows the nothing found to display.

    Please suggest me what Iam missing in this.


    Thanks in advance,

    Jee

    ReplyDelete

Popular Posts