Gridview in Java Web Applications using jQuery DataTable

DOWNLOAD In every data driven web application, displaying data in tables is inevitable. In ASP.NET we have Gridview to serve thi...




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!


Related

jQuery UI 2482619785081589395

Post a Comment

  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. Hello could you please provide the demo and source code of insert, update, delete operations in grid through controls using jquery?

    ReplyDelete
  4. Priya,

    Excellent article.

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

    Thanks

    ReplyDelete
  5. 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
  6. can u explain using action class

    ReplyDelete
  7. how can i use this gridview with mysql database with paging..
    please give reply it's urgent

    ReplyDelete
    Replies
    1. Hi,

      You just have to write code to get data from mysql table in FetchDatafromDb method in the above example.

      Yo can also take a look at this,

      http://datatables.net/development/server-side/jsp

      Hope this helps!

      Delete
  8. hi,
    first of all thanks for the share.it is very usefull.
    but i have a csv file that i don't know how many columns it contains( maybe one,2 or 5).i tried to make the constructor with var args but it shows that the result is always null.
    please can you help me ?

    ReplyDelete
    Replies
    1. Hi,

      Please download source from the link given and try it yourself to understand what is missing in you implementation.

      Also,to get immediate advice by experts, please post your code and explain your problem in any of the programming forums like http://stackoverflow.com

      Hope this helps!

      Delete
    2. thanks for the advice but i changed the code to achieve my goal
      it works fine for me now :)

      Delete
    3. HI..
      I want more than 4 columns where i need to edit..Please Help Me..

      Delete
  9. Great work!. thanks.
    I would like to know how to add 'editing' and 'deleting' to the same table?

    ReplyDelete
  10. Priya can you please explain with an example ,how to make table editable
    else please post a link that contain example

    ReplyDelete
    Replies
    1. Hi Krishna,

      There is an additional plugin called "Editable" available to be used along with Datatable. Check this out,

      http://www.codeproject.com/Articles/193068/Adding-data-management-CRUD-functionalities-to-the

      Hope this helps!

      Thanks,
      Priya

      Delete
    2. Thanks priya 4 reply,
      I have checked out that plugin
      I think that plugin is not open source,it is licensed one.
      I know that but it is not suitable to my project

      Is there any other plugin to solve this problem

      Delete
    3. Check out jEditable jquery plugin,

      http://www.appelsiini.net/projects/jeditable
      http://www.datatables.net/examples/api/editable.html

      Hope this helps!

      Delete
  11. There is another library of classes that allow you full CRUD capabilities for DataTables. It is called JED. That's short for Java Editor for DataTables. You can find it here: http://jed-datatables.net/jed/

    ReplyDelete
    Replies
    1. The URL has changed a little. Just use the domain name. http://jed-datatables.net

      Delete
  12. Hi, I followed you sets and the project is executed without errors but the datatable does not get the data from csv...Any help!

    ReplyDelete
    Replies
    1. It works perfectly for me. I suggest you to post your code in any tech forums to get immediate help.

      Delete
    2. Hi Priya

      I able to use the examples provided by you .thanks for the URL.
      but i have a question , i have to process multiple values , because i want to process the data for one row TR of table having say 4 different TD values of table

      How can i process this ?

      Delete
  13. Hi,

    Very good approach. Congratualtions!

    You have some version using javascript instead server-side (jsp).

    Thanks a lot.

    ReplyDelete
  14. Hi,
    The code is working fine.But! when i say next after 110 records the next and last buttons are coming down..How do i make those all button in single row??

    ReplyDelete
  15. its very useful thank u...

    ReplyDelete
  16. Excellent! Thank you for the reference!

    ReplyDelete
  17. Hello, do you have the same explaining how to accomplish in a JSF app?

    ReplyDelete
  18. Please upload file again...this link is broken

    ReplyDelete

emo-but-icon

SUBSCRIBE


item