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 getCompanyList() {

	List listOfCompany = new LinkedList();
	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.
 





Gridview in Struts2 using jQuery DataTable plugin












Ajax based Gridview in Struts2 using jQuery DataTable plugin

Company Country Year Revenue

 
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 aaData;
    
    	public List getAaData() {
    		return aaData;
    	}
    
    	public void setAaData(List aaData) {
    		this.aaData = aaData;
    	}
    
    	public String execute() {
    		aaData = BusinessService.getCompanyList();
    		return SUCCESS;
    	}
    }
    

     

    struts.xml

     

    
      	
    		
                            
                               true
                              true
                           
    		
    	
    	
    
    

    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

    
    Struts2
    
    	struts2
    	
    	 org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
            
    
    
    	struts2
    	/*
    
    
    	index.jsp
    
    
    

     

    Demo

     
    Gridview in Struts2 using jQuery DataTable plugin
     
    download

    17 Comments

    1. 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.

    2. 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!

    3. 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

    4. 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

    5. 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

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

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

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

      • war file have source code

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

    9. Hi, thankyou very much it works for me

    10. 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..

    11. this is not working.