Pages Navigation Menu

Coding is much easier than you think

GridView in Struts2 using jQuery DataTable via Ajax

 
In this post, I am going to explain on how to use DataTable plugin to display data in Gridview format with pagination feature in Struts 2 web application.
 
Gridview in Struts2 using jQuery DataTable plugin
 
DataTable is a jQuery plugin which adds a lot of functionality to plain HTML tables, such as filtering, paging sorting, changing page length, server side processing etc.
 

Library

In this example, I am going to retrieve values from a csv file and display it in html table. For this, I am going to use OpenCSV library which simplifies the work of parsing CSV files. Here the Data table will load the data by making an Ajax call.
 
Note:
• Refer the article on how to Read / Write CSV file in Java using Opencsv library/ .
 
Since the response to be generated from the action class is of type JSON, So to handle it you need struts2-json-plugin-2.x.x.jar. This plugin allows you to serialize the Action class attribute (which has getter and setter) into a JSON object. Refer this article here for more detail.
 
Now create a dynamic web project in eclipse and create two folders named ‘js’ and ‘css’ under WebContent, and add the following javascript files from DataTable to the ‘js’ folder

• jquery.dataTables.js
• jquery.js

Add the following css files from DataTable & jQuery ui to ‘css’ folder.

• demo_page.css
• demo_table_jui.css
• jquery-ui-x.x.x.css
 
** UPDATE: Struts 2 Complete tutorial now available here.
 
Download the csv file from which the data is to be read from here and place it under src folder, This files contains four columns – company, country, revenue, and year.
 

Project Structure

 
Folder structure - Gridview - Struts2 - DataTable 2
 

Model class

 
Create a model class that gets and sets the data from the four columns (company, country, revenue, and year) of the csv file.
 

package com.model;

public class RevenueReport {

	public RevenueReport(String company, String country, String year,
			String revenue) {
		this.company = company;
		this.country = country;
		this.year = year;
		this.revenue = revenue;
	}

	private String company;
	private String country;
	private String year;
	private String revenue;

	public String getCountry() {
		return country;
	}

	public String getRevenue() {
		return revenue;
	}

	public String getCompany() {
		return company;
	}

	public String getYear() {
		return year;
	}

	public void setCountry(String country) {
		this.country = country;
	}

	public void setRevenue(String revenue) {
		this.revenue = revenue;
	}

	public void setCompany(String company) {
		this.company = company;
	}

	public void setYear(String year) {
		this.year = year;
	}
}

 

Business class

 
Create a Business Service class that would fetch data from the csv file using model class.
 

package com.service;

import java.io.*;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;

import au.com.bytecode.opencsv.CSVReader;

import com.model.RevenueReport;

public class BusinessService {

public static List<RevenueReport> getCompanyList() {

	List<RevenueReport> listOfCompany = new LinkedList<RevenueReport>();
	String fileName = "Company_Revenue.csv";

	InputStream is = Thread.currentThread().getContextClassLoader()
			.getResourceAsStream(fileName);
	BufferedReader br = new BufferedReader(new InputStreamReader(is));

	try {
		CSVReader reader = new CSVReader(br);
		String[] row = null;
		while ((row = reader.readNext()) != null) 
		{
		listOfCompany.add(new RevenueReport(row[0], row[1], row[2],	row[3]));
		}
		reader.close();
	} catch (IOException e) {
		System.err.println(e.getMessage());
	}
	return listOfCompany;
}
}

 

Jsp

 
Now create the jsp file to display the data fetched from csv file in html table and enhance the table features using DataTable plugin.
 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Gridview in Struts2 using jQuery DataTable plugin</title>

<link href="css/demo_table_jui.css" rel="stylesheet" />
<link href="css/jquery-ui.css" rel="stylesheet" />
<link href="css/demo_page.css" rel="stylesheet" />

<script src="js/jquery.js"></script>
<script src="js/jquery.dataTables.js"></script>
<script>
$(document).ready(function() {
	$(".jqueryDataTable").dataTable({
		"sPaginationType" : "full_numbers",
		"bProcessing" : false,
		"bServerSide" : false,
		"sAjaxSource" : "dataTablesAction",
		"bJQueryUI" : true,
		"aoColumns" : [
            { "mData": "company" },
            { "mData": "country" },
            { "mData": "year" },
            { "mData": "revenue" }
        ]
    } ); 
} );
</script>

</head>

<body id="dt_example">
<div id="container">
<h1>Ajax based Gridview in Struts2 using jQuery DataTable plugin</h1>
<div id="demo_jui">
	<table class="display jqueryDataTable">
	<thead>
	<tr>
		<th>Company</th>
		<th>Country</th>
		<th>Year</th>
		<th>Revenue</th>
	</tr>
	</thead>
	<tbody>
	</tbody>
	</table>
</div>
</div>
</body>
</html>

 
Do read :

  • jQuery Tutorial for Beginners
  • Autocomplete in Java web application using jQuery
  • Tab Style Login and Signup example using jQuery in Java web application
  •  

    Action class

     
    In reply to each request for information that DataTables makes to the server, it expects to get a well formed JSON object with the parameter below.

    1. aaData- The data in a 2D array.
     

    package com.action;
    
    import java.util.List;
    
    import com.model.RevenueReport;
    import com.opensymphony.xwork2.Action;
    import com.service.BusinessService;
    
    public class GridViewAction implements Action {
    
    	private List<RevenueReport> aaData;
    
    	public List<RevenueReport> getAaData() {
    		return aaData;
    	}
    
    	public void setAaData(List<RevenueReport> aaData) {
    		this.aaData = aaData;
    	}
    
    	public String execute() {
    		aaData = BusinessService.getCompanyList();
    		return SUCCESS;
    	}
    }
    

     

    struts.xml

     

    <struts>
      	<package name="default" extends="json-default">
    		<action name="dataTablesAction" class="com.action.GridViewAction">
                            <result type="json">
                               <param name="excludeNullProperties">true</param>
                              <param name="noCache">true</param>
                           </result>
    		</action>
    	</package>
    	
    </struts>
    

    Note that I have extended “json-default” package instead of struts-default package and I have set the result type to json, I have explained about the reason for extending “json-default” package in the article AJAX implementation in Struts 2 using JQuery and JSON, please refer the mentioned link if you are not aware of the same.
     

    Recommended reading:

  • Ajax in struts 2 implementation without jQuery library
  •  

    web.xml

     
    Make sure you have done servlet mapping properly in web.xml file as shown below

    <web-app>
    <display-name>Struts2</display-name>
    <filter>
    	<filter-name>struts2</filter-name>
    	<filter-class>
    	 org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
            </filter-class>
    </filter>
    <filter-mapping>
    	<filter-name>struts2</filter-name>
    	<url-pattern>/*</url-pattern>
    </filter-mapping>
    <welcome-file-list>
    	<welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    </web-app>
    

     

    Demo

     
    Gridview in Struts2 using jQuery DataTable plugin
     
    download

    About Mohaideen Jamil


    Am currently working as a Struts 2 Developer in a reputed IT Organisations. I can help you with teaching Core java and Struts 2. Follow me on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.

    • dharambir kumar

      sir my Q. is i want to display data from mysql db and remain all feature will be same as a like Gridview in Struts2 using jQuery DataTable plugin,i have need olny display data from db with search,,can you help me sir .very very thanks in advance.

    • Rajesh

      Hi, How we can increase and decrease column in this DataGrid. Actually i am try to increase the no. of column but i got a error as follows:

      “DataTables warning (table id = ‘DataTables_Table_0′): Requested unknown parameter ‘0’ from the data source for row 0″

      thanks in advance!

    • jahurul

      please can you say me , where location of grid.jsp in the strut.xml file , and please describe how the page is work and mapping

    • NansJames

      Hi, am using to get the database values which are set in list
      so am iterating like below:


      If i put in then the div tag to show entries and search and below div tag to show first,previous and next button are not displaying. If i remove then div tags are displaying and no entries are displaying as it will come out of the table.

      Please tell what will the problem

    • http://gravatar.com/rajibkumarmohanty Rajib

      Hi,
      I need datagrid should be uploaded after the login but I applied your application but i am getting error.Please find the error.
      no default parameter defined for result of type json
      11:00:52,297 ERROR [org.apache.struts2.dispatcher.Dispatcher] (ServerService Thread Pool — 38) Dispatcher initialization failed: Unable to load configuration. – package – vfs:/D:/fsw/jboss-eap-6.1/bin/content/NSS_Site_Creation1.war/WEB-INF/classes/struts.xml:49:53
      at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:69) [xwork-core-2.3.1.2.jar:2.3.1.2]
      at org.apache.struts2.dispatcher.Dispatcher.init_PreloadConfiguration(Dispatcher.java:390) [struts2-core-2.3.1.2.jar:2.3.1.2]
      at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:436) [struts2-core-2.3.1.2.jar:2.3.1.2]
      at org.apache.struts2.dispatcher.FilterDispatcher.init(FilterDispatcher.java:195) [struts2-core-2.3.1.2.jar:2.3.1.2]
      at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:416) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1]
      at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:3225) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1]
      at org.apache.catalina.core.StandardContext.start(StandardContext.java:3791) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1]
      at org.jboss.as.web.deployment.WebDeploymentService.doStart(WebDeploymentService.java:156) [jboss-as-web-7.2.1.Final-redhat-10.jar:7.2.1.Final-redhat-10]
      at org.jboss.as.web.deployment.WebDeploymentService.access$000(WebDeploymentService.java:60) [jboss-as-web-7.2.1.Final-redhat-10.jar:7.2.1.Final-redhat-10]
      at org.jboss.as.web.deployment.WebDeploymentService$1.run(WebDeploymentService.java:93) [jboss-as-web-7.2.1.Final-redhat-10.jar:7.2.1.Final-redhat-10]
      at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) [rt.jar:1.7.0_60]
      at java.util.concurrent.FutureTask.run(FutureTask.java:262) [rt.jar:1.7.0_60]
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [rt.jar:1.7.0_60]
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [rt.jar:1.7.0_60]
      at java.lang.Thread.run(Thread.java:745) [rt.jar:1.7.0_60]
      at org.jboss.threads.JBossThread.run(JBossThread.java:122)
      Caused by: The package name ‘default’ at location package – vfs:/D:/fsw/jboss-eap-6.1/bin/content/NSS_Site_Creation1.war/WEB-INF/classes/struts.xml:49:53 is already been used by another package at location package – vfs:/D:/fsw/jboss-eap-6.1/bin/content/NSS_Site_Creation1.war/WEB-INF/classes/struts.xml:14:68 – package – vfs:/D:/fsw/jboss-eap-6.1/bin/content/NSS_Site_Creation1.war/WEB-INF/classes/struts.xml:49:53
      at com.opensymphony.xwork2.config.impl.DefaultConfiguration.addPackageConfig(DefaultConfiguration.java:124) [xwork-core-2.3.1.2.jar:2.3.1.2]
      at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.addPackage(XmlConfigurationProvider.java:494) [xwork-core-2.3.1.2.jar:2.3.1.2]
      at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.loadPackages(XmlConfigurationProvider.java:278) [xwork-core-2.3.1.2.jar:2.3.1.2]
      at org.apache.struts2.config.StrutsXmlConfigurationProvider.loadPackages(StrutsXmlConfigurationProvider.java:112) [struts2-core-2.3.1.2.jar:2.3.1.2]
      at com.opensymphony.xwork2.config.impl.DefaultConfiguration.reloadContainer(DefaultConfiguration.java:204) [xwork-core-2.3.1.2.jar:2.3.1.2]
      at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:66) [xwork-core-2.3.1.2.jar:2.3.1.2]
      … 15 more

    • rama

      How to display xml data. I am unable to display the entire xml fetched from DB

    • ramesh

      I am not getting the screen. I is simply showing the title and column names of the table. Please help.

    • kavita saini

      Instead of war file, can u share the source code of the example

      • http://www.simplecodestuffs.com Mohaideen Jamil

        war file have source code

        • adfsaf

          war file contains compiled source code, in other words encrypted and unreadable class files.

    • Maheswari

      Hi, thankyou very much it works for me

    • suresh

      Hi i am having doubt in display tag in struts.please help me.

      Dynamically i am trying to display the content using display tag.

      while executing i am getting error(manually i deleted one row , for insertion it is working fine.). we can’t achieve dynamic using display tag?? please help me..

      • http://www.simplecodestuffs.com Mohaideen Jamil

        Can you please share your stacktrace?

        • http://www.simplecodestuffs.com Mohaideen Jamil

          are you using another plugin for this implementation ??

    • rahul

      this is not working.

      • http://www.simplecodestuffs.com Mohaideen Jamil

        This code works fine.. Please share your stack trace