Saturday, 2 February 2013

Gridview in Java Web Applications using jQuery DataTable

In every data driven web application, displaying data in tables is inevitable. In ASP.NET we have Gridview to serve this purpose with many predefined options like paging, sorting, editing etc. But in Java, there is no such control that is just like GridView. JTable from java swing framework can be used in console applications but for web application there is no such inbuilt component. Therefore, the best solution to display data in tables in Java is, to use DataTable, a jQuery plugin that enhances HTML tables in terms of features, look and interactivity. In this post, I am going to explain with example on how to use DataTable plugin to display data in Java web application(JSP page).




Before proceeding to the example, it is good to know the features that DataTable plugin offers to any table,

  • Variable length pagination
  • On-the-fly filtering
  • Multi-column sorting with data type detection
  • Smart handling of column widths
  • Display data from almost any data source
  • Scrolling options for table viewport
  • Fully internationalisable
  • jQuery UI ThemeRoller support
  • Rock solid - backed by a suite of 2900 unit tests
  • Wide variety of plug-ins inc. Editor, TableTools, FixedColumns and more
  • It's free!
In this example, I am going to retrieve values from a csv file and display it in html table. To read the csv file, I am using OpenCSV java library that simplifies the work of parsing CSV files. You can also code to retrieve data from database instead of reading from CSV file. 

1. First of all download all required libraries,
2. Create a dynamic web project in eclipse. Look for opencsv-x.x.jar in the opencsv download folder and add it classpath of the project.

3. Create two folders under YourProject/Webcontent and name it as 'js' and 'css'. Add the following javascript files from DataTable download to the 'js' folder you just created.

  • jquery.dataTables.js
  • jquery.js
Add the following css files  from DataTable download and jquery ui download to 'css' folder.
  • demo_page.css
  • demo_table_jui.css
  • demo_table.css
  • jquery-ui-x.x.x.css
4. Download the csv file from which the data is to be read from here and add it under YourProject/src folder. This css files contains four columns - country,revenue,sales manager,year.

5. Create a new jsp file under WebContent and the folder structure should look like shown below.


6. Now the project setup is done and we can start creating classes to pull data from csv file. First create a model class that gets and sets the data from the four columns - country,revenue,sales manager,year in the csv file. Create a java class under src folder and name it as "SalesReport.java". Copy and paste the below code in SalesReport.java file.

public class SalesReport {

    public SalesReport(String country,String revenue, String salesmanager,String year)
    {      
        this.country = country;
        this.revenue = revenue;
        this.salesmanager = salesmanager;
        this.year=year;
    }
      
    private String country;
    private String revenue;
    private String salesmanager;
    private String year;
  
 public String getCountry() {
  return country;
 }
 
 public String getRevenue() {
  return revenue;
 }
 
 public String getSalesmanager() {
  return salesmanager;
 }
 
 public String getYear() {
  return year;
 }
 
 public void setCountry(String country) {
  this.country = country;
 }
 
 public void setRevenue(String revenue) {
  this.revenue = revenue;
 }
 
 public void setSalesmanager(String salesmanager) {
  this.salesmanager = salesmanager;
 }
 
 public void setYear(String year) {
  this.year = year;
 }
}



7. Next step is to create a class that would fetch data from the csv file using SalesReport model class. Create a class and name it as, "FetchDataFromDb.java". Copy and paste the below the below code in it.



import au.com.bytecode.opencsv.CSVReader;
import SalesReport;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;


public class FetchDataFromDb {
 
 private static List<salesreport> SalesData = null;
 
 public static List<salesreport> GetSalesData() throws IOException{
  
  if(SalesData==null){   
   SalesData=new LinkedList<salesreport>();
   String csvFilename = "country_revenue.csv";
   InputStream is =  Thread.currentThread().getContextClassLoader().getResourceAsStream("com/programmingfree/salesreport/"+csvFilename);
   BufferedReader br = new BufferedReader(new InputStreamReader(is));
   CSVReader csvReader = new CSVReader(br);
   String[] row = null;
   while((row = csvReader.readNext()) != null) {   
      SalesData.add(new SalesReport(row[0],row[1],row[2],row[3]));        
   }      
   csvReader.close();   
  }    
  return SalesData;  
 }    
}


8. Final step is to create jsp file to display the data fetched from csv file in html table and enhance the table with features using DataTable plugin. Copy and paste the below code in the JSP file that is already created for this purpose.


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" import="*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>GridView for Java - jQuery Data Table</title>
<!-- CSS -->
<link href="css/demo_page.css" rel="stylesheet" type="text/css" />
<link href="css/demo_table.css" rel="stylesheet" type="text/css" />       
<link href="css/demo_table_jui.css" rel="stylesheet" type="text/css" />
<link href="css/jquery-ui-1.8.24.custom.css" rel="stylesheet" type="text/css" media="all" />
<!-- Scripts -->
<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/jquery.dataTables.js" type="text/javascript"></script>
 <script type="text/javascript">
        $(document).ready(function () {
            $("#sales").dataTable({
                "sPaginationType": "full_numbers",
                "bJQueryUI": true               
            });
        });
 </script>
</head>
<body id="dt_example">
<div id="container">
<h1>Gridview for Java using jQuery DataTable plugin</h1>
<div id="demo_jui">
<table id="sales" class="display">
              <thead>
                  <tr>
                      <th><u>Country</u></th>
                      <th><u>Revenue</u></th>
                      <th><u>Sales_Manager</u></th>
                      <th><u>Year</u></th>
                  </tr>
              </thead>
              <tbody>
              <% for(SalesReport c: FetchDataFromDb.GetSalesData()){ %>
        <tr>
          <td><%=c.getCountry()%></td>
          <td><%=c.getRevenue()%></td>
          <td><%=c.getSalesmanager()%></td>
          <td><%=c.getYear()%></td>
        </tr>
      <% } %>
              </tbody>
          </table>
          </div>
 </div>
</body>
</html>

That is all. We are done and you will now be able to view a table that is sortable, searchable on all fields with paging features. See screenshot below, the table is searched with the year "2010" and the results are produced accordingly. 






Download source code from above link and import to Eclipse IDE. Run the project on Tomcat server to understand this better. 

Caution
According to the documentation the HTML table should be well formed with <thead> and <tbody> tags like the example given below,

<table id="table_id">
    <thead>
        <tr>
            <th>Column 1</th>
            <th>Column 2</th>
            <th>etc</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Row 1 Data 1</td>
            <td>Row 1 Data 2</td>
            <td>etc</td>
        </tr>
        <tr>
            <td>Row 2 Data 1</td>
            <td>Row 2 Data 2</td>
            <td>etc</td>
        </tr>
    </tbody>
</table>


There are many other things you can add to this table like column filteringrow grouping, row editing and more using other plugins that can be used along with dataTable plugin.

Please leave your comments and queries about this post in the comment sections in order for me to improve my writing skills and to showcase more useful posts. Thanks for reading!!


Subscribe to GET LATEST ARTICLES!


Most Shared - Last Week


12 comments:

  1. love the way you explained the whole process! thanks for sharing!

    Smith
    Quality Web Programmers

    ReplyDelete
  2. Very useful article. Thanks for the detailed explanation!

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. please provide the code to perform edit,Delete and Add operation in the grid view using java

      Delete
    2. Hi Barkha,

      May be I will try my level best to write a post on performing simple crud operations with data table this weekend. Come back again after this weekend to know whether I have done that or not. If you don't find anything after this weekend here, please excuse, it would be definitely because of my tight schedule.

      Thanks,
      Priya

      Delete
    3. Hi Barkha,

      Please take a look at this, this is what you were referring to,

      Editable (CRUD) web tables in J2EE

      Delete
  4. Hello could you please provide the demo and source code of insert, update, delete operations in grid through controls using jquery?

    ReplyDelete
  5. Priya,

    Excellent article.

    I am too eagerly looking for insert, update, delete operations using Jquery and Java.

    Thanks

    ReplyDelete
  6. Priya

    I would like to know what is the difference between using bServerSide and calling <% for(SalesReport c: FetchDataFromDb.GetSalesData()){ %>? What are the advantages and disadvantages?

    Thanks

    ReplyDelete