Pages Navigation Menu

Coding is much easier than you think

Setting up jQuery jTable plugin in Servlets and JSP

Posted by in J2EE, Java, jQuery, jTable | 6 comments

 
In this article we will learn to setup jTable and dependent libraries in a Java web application.
 
Integrating-jQuery-jTable-plugin-with-Struts2-framework
 
For all who do not know what exactly jTable is, it is a jQuery plugin which is used to create AJAX based CRUD tables without coding HTML or Javascript.
 
Let us take a look at what happens if we are not using a Jquery Plugin for front end Table data management.

Using Java & Javascript:

Pre-requisites for usage:

  • Must be a expertise in java & javascript
  • A lot of time on hand
  • Last but not the least patience

 
Now if the project requirement for this table changes at last moment one would pull their hair out and end up resembling a Joker
 
Joker jTable
 
jTable has a few advantages over the above, some of them being:

  • Automatically creates HTML table and loads records from server using AJAX.
  • jTable uses just a div id and automatically generates html table inside the div
  • It uses jQuery UI dialog that pops up when the user clicks on add, edit or update record buttons
  • Shows animations for create/delete/edit operations on the table.
  • Supports server side paging & sorting using AJAX.
  • Supports master/child tables.
  • Supports several pre defined color themes; In this example I have used metro blue theme for my project.

And there are lot other features than mention above, to know more please read on its official home page.
 

Steps done to set up our application for jTable

 
Libraries required

 
Now to start with demonstration of above topic, let us Create a Dynamic Web Project in Eclipse, with following project structure.
 
jtable setup in servlet
 
As show in the image download the required library mentioned and place it in js and css folder of eclipse work-space, and refer these files in the head section in the jsp as shown below.
 
Setup done from the browser perspective: jTable
 
jTable plugin allows you to issue an ajax request via jQuery plugin and expects a JSON object as a response, hence the following configuration needs to be made in Jsp file
 

Jsp Page

 

<!DOCTYPE html>
<html>
<head>
<title>jQuery jTable Setup in java</title>
<!-- jTable Metro styles. -->
<link href="css/metro/blue/jtable.css" rel="stylesheet" type="text/css" />
<link href="css/jquery-ui-1.10.3.custom.css" rel="stylesheet" type="text/css" />
<!-- jTable script file. -->
<script src="js/jquery-1.8.2.js" type="text/javascript"></script>
<script src="js/jquery-ui-1.10.3.custom.js" type="text/javascript"></script>
<script src="js/jquery.jtable.js" type="text/javascript"></script>
<script type="text/javascript">
	$(document).ready(function() {
		$('#StudentTableContainer').jtable({
			title : 'Students List',
			actions : {
				listAction : 'Controller?action=list'
			},
			fields : {
				studentId : {
					title : 'Student Id',
					width : '30%',
					key : true,
					list : true,
					create : true
				},
				name : {
					title : 'Name',
					width : '30%',
					edit : false
				},
				department : {
					title : 'Department',
					width : '30%',
					edit : true
				},
				emailId : {
					title : 'Email',
					width : '20%',
					edit : true
				}
			}
		});
		$('#StudentTableContainer').jtable('load');
	});
</script>

</head>
<body>
<div style="text-align: center;">
	<h4>jQuery jTable Setup in java</h4>
	<div id="StudentTableContainer"></div>
</div>
</body>
</html>

 
As you can see, jTable just needs a div element as the only HTML tag. It fields options are explained below:

title: Title of the table.
actions: URLs of actions that are used to create/delete/update/list records.
fields: It defines the field names that represent columns of the record. Note that the field name should exactly match the instance variable defined in the model class.
 
In the jsp above I have only provided action url for listAction for demonstration purpose, we can include action for add,edit and delete functionality as well, which we will learn in a while. The load method of jTable is fired when page is loaded which in turn trigger listAction to get records from the server.
 
Setup done from the server’s perspective: Servlet
 
In Servlet, we are going to use a JSON library to convert Java objects(studentList) to JSON strings that will be parsed by jTable pugin in the JSP page and will be displayed on the web page.This conversion of Java Object to Json format is done using Google gson jar.

 

Controller

 

package com.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.model.Student;

public class Controller extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private HashMap<String, Object> JSONROOT = new HashMap<String, Object>();

	public void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	
	String action = request.getParameter("action");
	if ( action != null)
	{
		List<Student> studentList = new ArrayList<Student>();

		Gson gson = new GsonBuilder().setPrettyPrinting().create();
		response.setContentType("application/json");

		if (action.equals("list"))
		{
			try
			{
			// Add data to Student list
			studentList.add(new Student(1, "Haripriya", "IT", "[email protected]"));
			studentList.add(new Student(2, "Dinesh", "ECE", "[email protected]"));
			studentList.add(new Student(3, "Prabhu", "MECH", "[email protected]"));
			studentList.add(new Student(4, "Badru", "ECE", "[email protected]"));
			studentList.add(new Student(5, "Lahir nisha", "CSC", "[email protected]"));
			studentList.add(new Student(6, "Nilafar nisha", "CSC", "[email protected]"));
			studentList.add(new Student(7, "Jamil", "ECE", "[email protected]"));
			studentList.add(new Student(8, "Mahes", "ECE", "[email protected]"));
			studentList.add(new Student(9, "Lourde", "IT", "[email protected]"));

			//Return in the format required by jTable plugin
			JSONROOT.put("Result", "OK");
			JSONROOT.put("Records", studentList);
			
			// Convert Java Object to Json
			String jsonArray = gson.toJson(JSONROOT);
			System.out.println(jsonArray);

			response.getWriter().print(jsonArray);
			}
			catch(Exception ex){
				JSONROOT.put("Result", "ERROR");
				JSONROOT.put("Message", ex.getMessage());
				String error = gson.toJson(JSONROOT);
				response.getWriter().print(error);
			}
		}
		}
	 }
}

 
In case of read operations in jTable, Result property must be “OK” if operation is successful. If an error occurs, then Result property must be “ERROR”. If Result is “OK”, the Records property will contain an array of records defined in the servlet. If it’s ERROR, a Message property will contain an error message to show to the user. A sample return value for listAction is show below
 
{“Result”:”OK”,”Records”:[
{
“studentId”: 2,
“name”: “Bashit”,
“department”: “EEE”,
“emailId”: “[email protected]
},
{
“studentId”: 3,
“name”: “Haripriya”,
“department”: “IT”,
“emailId”: “[email protected]
}
]}
 

Model Class

 
Create the Model class , which will have getters and setters for fields used in jsp
 

package com.model;

public class Student {

	public Student() {
	}

	public Student(int studentId, String name, String department, String emailId) {
		this.studentId = studentId;
		this.name = name;
		this.department = department;
		this.emailId = emailId;
	}

	private int studentId;
	private String name;
	private String department;
	private String emailId;

	public int getStudentId() {
		return studentId;
	}

	public String getName() {
		return name;
	}

	public String getDepartment() {
		return department;
	}

	public String getEmailId() {
		return emailId;
	}

	public void setStudentId(int studentId) {
		this.studentId = studentId;
	}

	public void setName(String name) {
		this.name = name;
	}

	public void setDepartment(String department) {
		this.department = department;
	}

	public void setEmailId(String emailId) {
		this.emailId = emailId;
	}
}

 

web.xml

Make sure you have done servlet mapping properly in web.xml file. An example of this is given below,
 

<welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
  <servlet-name>Controller</servlet-name>
  <servlet-class>com.servlet.Controller</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>Controller</servlet-name>
  <url-pattern>/Controller</url-pattern>
</servlet-mapping>

 

Demo

 
jquery-jtable-in-struts-2
 
 
Now on including action for create, update and delete in jsp page as below

actions : {
          listAction: 'Controller?action=list',
          createAction:'Controller?action=create',
          updateAction: 'Controller?action=update',
          deleteAction: 'Controller?action=delete'
}

 
No on running with the above changes, the demo looks like below
Integrating-jQuery-jTable-plugin-with-Struts2-framework
 
On clicking ‘Add new record’
Struts-2-using-jTable-jQuery-plug-in-Create-record
 
On clicking edit button
Struts-2-jTable-jQuery-plug-in-Update-record
 
On clicking delete button
Struts-2-jTable-jQuery-plug-in-Delete-record
 
Note :
 
In the above program I have not included the logic for create, delete and update functions at server side. In the article CRUD Operations in Java Web Applications using jTable jQuery plugin via Ajax I have implemented CRUD operation, and in the article Pagination in Java Web Applications using jQuery jTable plugin I have implemented paging feature using the same plugin.
 
download
 

Reference

jTable official website
AJAX based CRUD tables using ASP.NET MVC 3 and jTable jQuery plug-in
Wikipedia : JSON
 

Read More

Gridview in Servlets using jQuery DataTables plugin

Posted by in Ajax, J2EE, jQuery, Servlet | 8 comments

 
In this article we shall learn the basic coding that required to create JQuery DataTable using JSON passed by servlet. 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.
 
Gridview-in-Java-web-application-using-jQuery-DataTable-plugin
 

Library required

 

Installation

 
Above download will provide two JQuery plugin jquery.js and jquery.dataTables.js

<script src="js/jquery.js"></script>
<script src="js/jquery.dataTables.js"></script>

 
Default stylesheet which shipped with latest DataTable download package

<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" />

 

Project Structure

Create a dynamic web project with following folder structure and place the above files as shown.
 
Folder-structure-Gridview-Java-DataTable
 

Model class

 

package com.model;

public class RevenueReport {

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

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

	public String getCountry() {
		return country;
	}

	public int getRevenue() {
		return revenue;
	}

	public String getCompany() {
		return company;
	}

	public int getYear() {
		return year;
	}

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

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

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

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

 

Recommended reading:

 

Business class

 
This Business Service class which provides static data using model class.
 

package com.service;

import java.util.LinkedList;
import java.util.List;

import com.model.RevenueReport;

public class BusinessService {

public static List<RevenueReport> getCompanyList() {

	List<RevenueReport> listOfCompany = new LinkedList<RevenueReport>();

	listOfCompany.add(new RevenueReport("Bosch", "Germany",2012, 40000));
	listOfCompany.add(new RevenueReport("XYZ", "India",2014, 10000));
	listOfCompany.add(new RevenueReport("Robotics", "United Kingdom",2011, 35000));
	listOfCompany.add(new RevenueReport("Merch", "USA",2010, 20000));
	listOfCompany.add(new RevenueReport("Foxtron", "Indonesia",2009, 15000));
	listOfCompany.add(new RevenueReport("Benz", "Germany",2013, 50000));
	listOfCompany.add(new RevenueReport("Audi", "United Kingdom",2012, 60000));
	listOfCompany.add(new RevenueReport("Hyat", "France",2011, 30000));
	listOfCompany.add(new RevenueReport("HCL", "India",2007, 23000));
	listOfCompany.add(new RevenueReport("CTS", "USA",2010, 42000));
	listOfCompany.add(new RevenueReport("Accenture", "France",2008, 15000));
	listOfCompany.add(new RevenueReport("Air India", "India",2005, 10000));
	listOfCompany.add(new RevenueReport("Kingfisher", "India",2011, 8000));
	listOfCompany.add(new RevenueReport("Vodaphone", "Netharland",2006, 45000));
	
	return listOfCompany;
}
}

 

Jsp

 

<!DOCTYPE html>
<html>
<head>
<title>Gridview in Servlet 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>
// Ajax call to Servlet to display data via DataTables
$(document).ready(function() {
	$(".jqueryDataTable").dataTable({
		"sPaginationType" : "full_numbers",
		"bProcessing" : false,
		"bServerSide" : false,
		"sAjaxSource" : "displayData",
		"bJQueryUI" : true,
		"aoColumns" : [
            { "mData": "company" },
            { "mData": "country" },
            { "mData": "year" },
            { "mData": "revenue" }
        ]
    } );
} );
</script>
</head>

<body id="dt_example">
<div id="container">
<h1>Ajax based Gridview 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>

 

DataTable Parameters class

 
In reply to each request for information that DataTables makes to the server, it expects to get a well formed JSON object with some parameters.So Create a DataTable Parameters class with all those required parameters
 

package com.dataTable;

import java.util.List;

import com.model.RevenueReport;

public class DataTableParameters {
	// Data table plugin parameter
	int iTotalRecords;
	int iTotalDisplayRecords;
	String sEcho;
	String sColumns;
	List<RevenueReport> aaData;

	public int getiTotalRecords() {
		return iTotalRecords;
	}

	public void setiTotalRecords(int iTotalRecords) {
		this.iTotalRecords = iTotalRecords;
	}

	public int getiTotalDisplayRecords() {
		return iTotalDisplayRecords;
	}

	public void setiTotalDisplayRecords(int iTotalDisplayRecords) {
		this.iTotalDisplayRecords = iTotalDisplayRecords;
	}

	public String getsEcho() {
		return sEcho;
	}

	public void setsEcho(String sEcho) {
		this.sEcho = sEcho;
	}

	public String getsColumns() {
		return sColumns;
	}

	public void setsColumns(String sColumns) {
		this.sColumns = sColumns;
	}

	public List<RevenueReport> getAaData() {
		return aaData;
	}

	public void setAaData(List<RevenueReport> aaData) {
		this.aaData = aaData;
	}
}

 

Servlet implementation

 

package com.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.dataTable.DataTableParameters;
import com.model.RevenueReport;
import com.service.BusinessService;

public class DataTableServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("application/json");
		// Call business service class to get list of company
		List<RevenueReport> listOfCompany = BusinessService.getCompanyList();

		DataTableParameters dataTableParam = new DataTableParameters();
		// Set the list fetched in aaData
		dataTableParam.setAaData(listOfCompany);

		Gson gson = new GsonBuilder().setPrettyPrinting().create();
		// Convert Java Object to Json
		String json = gson.toJson(dataTableParam);

		response.getWriter().print(json);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

 

web.xml

Make sure you have done servlet mapping properly in web.xml file. An example of this is given below,
 

<web-app>
<servlet>
	<display-name>displayData</display-name>
	<servlet-name>displayData</servlet-name>
	<servlet-class>com.servlet.DataTableServlet</servlet-class>
</servlet>
<servlet-mapping>
	<servlet-name>displayData</servlet-name>
	<url-pattern>/displayData</url-pattern>
</servlet-mapping>
<welcome-file-list>
	<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

 

download
 

Reference

 
jQuery DataTables in Java Web Applications
 

Read More

AJAX in Servlet & jsp using JQuery – Java web application

Posted by in J2EE, Java, jQuery | 5 comments

 
jQuery-Ajax-Servlet-Jsp
 
Implementing Ajax features in a Java web application will be so easy if you are using JQuery library; Since this library provides built-in methods that can be used to enable Ajax. In this post, I am going to demonstrate the JQuery’s Ajax capability using on blur event in java web application.
 

Folder Structure

 
jquery-ajax-basic
 
As highlighted in the image download the jQuery library and place in js folder of eclipse work-space, and refer this jQuery files in the head section in the jsp, this jQuery file is responsible for the AJAX call made to the servlet and for updating the response back in the JSP.
 

Jsp Page

 

<html>
<head>
<title>AJAX in java web application using jQuery</title>
<script src="js/jquery-1.11.1.js" type="text/javascript"></script>
<script type="text/javascript" src="ajax.js"></script>
</head>
<body>
<form>
  <fieldset>
    <legend>AJAX implementation in JSP and Servlet using JQuery</legend>
    <br /> Enter your Name: <input type="text" id="userName" />
 </fieldset>

 <fieldset>
   <legend>Response from jQuery Ajax Request on Blur event</legend>
   <div id="ajaxResponse"></div>
 </fieldset>
</form>
</body>
</html>

 

JS File

 
File: ajax.js
In this file we will fire ajax via jquery get method to call java servlet

$(document).ready(function() {
	$('#userName').blur(function(event) {
		var name = $('#userName').val();
		$.get('JqueryServlet', {
			userName : name
		}, function(responseText) {
			$('#ajaxResponse').text(responseText);
		});
	});
});

 
Here when the user types a name in the “userName textbox” and click anywhere outside the textbox, then its blur event gets triggered and the ‘get’ function executes the Ajax GET request on the Servlet. Here the first argument of get method is the URL, second argument is a key-value pair that passes the parameter from JSP to Servlet and the third argument is a function that defines what is to be done with the response that is got back from the Servlet.
 
Note :
This get method is a shorthand Ajax function, which is equivalent to:

$.ajax({
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

 

Recommended reading:

  • Ajax implementation without jQuery library
  • jQuery Tutorial for Beginners
  •  

    Servlet

     
    Now let’s go on and write the servlet which handles this Ajax call

    package com.servlet;
    
    import java.io.IOException;
    import javax.servlet.ServletException;
    
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class JqueryServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    protected void doGet(HttpServletRequest request,
    	HttpServletResponse response) throws ServletException, IOException {
    
    	String userName = request.getParameter("userName");
    	if (userName.equals("")) {
    		userName = "User name cannot be empty";
    	} else {
    		userName = "Hello " + userName;
    	}
    	response.setContentType("text/plain");
    	response.getWriter().write(userName);
    }
    }
    

    I hope the code above is self explanatory.
     

    Another must read:

     

    Web.xml

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

    <web-app>
      <display-name>JqueryAjaxServlet</display-name>
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
      <servlet>
        <servlet-name>JqueryServlet</servlet-name>
        <servlet-class>com.servlet.JqueryServlet</servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>JqueryServlet</servlet-name>
        <url-pattern>/JqueryServlet/*</url-pattern>
      </servlet-mapping>
    </web-app>
    

     

    Demo

     
    AJAX-implementation-in-JSP-and-Servlet-using-JQuery
     
    On running the application the above webpage is generated, in which enter a value in the textbox and click anywhere outside the textbox, then you will see a welcome message saying “Hello (userName)”.

    Note: In our next article I have explained on how to return complex Java objects such as list, map, etc. as response to a ajax call.
     
    download
     

    Reference

     

    Read More

    Setting up jQuery jTable plugin in Struts 2 framework

    Posted by in jQuery, jTable, Struts 2 Tutorial, Struts-2 | 42 comments

     
    In this article we will learn to setup jTable and dependent libraries in Struts 2 web application. jTable is a jQuery plugin which is used to create AJAX based CRUD tables without coding HTML or Javascript, to know more about jTable please refer the article here
     

    Steps done to set up our application for jTable

     
    Libraries required for the setup,

     
    Now to start with demonstration of above topic, let us Create a Dynamic Web Project in Eclipse, with following project structure.
     
    jTable in struts 2
     
    As show in the image download the required library mentioned and place it in js and css folder of eclipse work-space, and refer these files in the head section in the jsp as shown below.
     
    Setup done from the browser perspective: jTable
     
    jTable plugin allows you to issue an ajax request via jQuery plugin and expects a JSON object as a response, hence the following configuration needs to be made in Jsp file
     

    Jsp Page

     
    File : jTable.jsp

    <html>
    <head>
    <title>jTable in Struts 2</title>
    <!-- jTable Metro theme -->
    <link href="css/metro/blue/jtable.css" rel="stylesheet" type="text/css" />
    <link href="css/jquery-ui-1.10.3.custom.css" rel="stylesheet"
    	type="text/css" />
    
    <!-- jTable script file. -->
    <script src="js/jquery-1.8.2.js" type="text/javascript"></script>
    <script src="js/jquery-ui-1.10.3.custom.js" type="text/javascript"></script>
    <script src="js/jquery.jtable.js" type="text/javascript"></script>
    <script type="text/javascript">
    	$(document).ready(function() {
    		$('#StudentTableContainer').jtable({
    			title : 'Students List',
    			actions : {
    				listAction : 'listAction'
    			},
    			fields : {
    				studentId : {
    					title : 'Student Id',
    					width : '30%',
    					key : true,
    					list : true,
    					create : true
    				},
    				name : {
    					title : 'Name',
    					width : '30%',
    					edit : false
    				},
    				department : {
    					title : 'Department',
    					width : '30%',
    					edit : true
    				},
    				emailId : {
    					title : 'Email',
    					width : '20%',
    					edit : true
    				}
    			}
    		});
    		$('#StudentTableContainer').jtable('load');
    	});
    </script>
    
    </head>
    <body>
    <div>
    	<h3>Integrating jTable jQuery plugin and Struts 2 framework</h3>
    	    <div id="StudentTableContainer"></div>
    </div>
    </body>
    </html>
    

     
    As you can see, jTable just needs a div container as the only HTML tag. It fields options are explained below:
    title: Title of the table.
    actions: URLs of actions that are used to create/delete/update/list records.
    fields: It defines the field names that represent columns of the record. Note that the field name should exactly match the instance variable defined in the model class.
     
    Setup done from the server’s perspective: Struts 2 Action class
     
    In the Action class, we are populating a list of type “Student”(Model). Since jTable accepts data only in Json format, so we are converting this List (Java Object) to Json(Javascript object Notation) format using struts2-json-plugin.jar.

    **Update:: In the article AJAX implementation in Struts 2 using JQuery and JSON I have explained about usage of struts2-json-plugin.jar clearly, So if you are not aware of how struts2-json-plugin works, then please go thorough the above mentiioned link.

     

    Action Class

     

    package com.simplecodestuffs.action;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import com.opensymphony.xwork2.Action;
    import com.simplecodestuffs.model.Student;
    
    public class JtableAction {
    
    	private List<Student> records = new ArrayList<Student>();
    	private String result;
    
    	public String list() {
    		// Add data to Student list
    		records.add(new Student(1, "Haripriya", "IT", "[email protected]"));
    		records.add(new Student(2, "Dinesh", "ECE", "[email protected]"));
    		records.add(new Student(3, "Prabhu", "MECH", "[email protected]"));
    		records.add(new Student(4, "Badru", "ECE", "[email protected]"));
    		records.add(new Student(5, "Lahir nisha", "CSC", "[email protected]"));
    		records.add(new Student(6, "Nilafar nisha", "CSC", "[email protected]"));
    		records.add(new Student(7, "Jamil", "ECE", "[email protected]"));
    		records.add(new Student(8, "Mahes", "ECE", "[email protected]"));
    		records.add(new Student(9, "Lourde", "IT", "[email protected]"));
    		result = "OK";
    
    		return Action.SUCCESS;
    	}
    
    	public List<Student> getRecords() {
    		return records;
    	}
    
    	public void setRecords(List<Student> records) {
    		this.records = records;
    	}
    
    	public String getResult() {
    		return result;
    	}
    
    	public void setResult(String result) {
    		this.result = result;
    	}
    }
    

     
    In case of read operations in jTable, Result property must be “OK” if operation is successful. If an error occurs, then Result property must be “ERROR”. If Result is “OK”, the Records property will contain an array of records defined in the action class. If it’s ERROR, a Message property will contain an error message to show to the user. A sample return value for listAction is show below
     

    {
    "Result":"OK",
    "Records":
    [{
    "studentId":1,
    "name":"Haripriya",
    "department":"IT",
    "emailId":"[email protected]"
    }]
    }
    

     

    Model Class

     
    Create the Model class which will have getters and setters for fields specified in jTable script.
     

    package com.simplecodestuffs.model;
    
    public class Student {
    
    	public Student() {
    	}
    
    	public Student(int studentId, String name, String department, String emailId) {
    		super();
    		this.studentId = studentId;
    		this.name = name;
    		this.department = department;
    		this.emailId = emailId;
    	}
    
    	private int studentId;
    	private String name;
    	private String department;
    	private String emailId;
    
    	public int getStudentId() {
    		return studentId;
    	}
    
    	public String getName() {
    		return name;
    	}
    
    	public String getDepartment() {
    		return department;
    	}
    
    	public String getEmailId() {
    		return emailId;
    	}
    
    	public void setStudentId(int studentId) {
    		this.studentId = studentId;
    	}
    
    	public void setName(String name) {
    		this.name = name;
    	}
    
    	public void setDepartment(String department) {
    		this.department = department;
    	}
    
    	public void setEmailId(String emailId) {
    		this.emailId = emailId;
    	}
    }
    

     

    Struts.xml

     

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
    <struts>
    <package name="default" extends="json-default">
       <action name="listAction" class="com.simplecodestuffs.action.JtableAction"
    	method="list">
    	<result type="json">/jTable.jsp</result>
      </action>
      <action name="getJSONResult" class="com.simplecodestuffs.action.JtableAction" method="list">
    	<result type="json" />
      </action>
    </package>
    </struts>
    

    Since jTable accepts data only in Json format, So in order to convert java object to json object I have extended json-default package instead of struts-default package, please refer article here for more detail on json-default package.
     

    Demo

     
    On running the application i got the following response
     
    Jtable exception
     
    Since I have not handled any exception, so the message displayed in error box is empty.
     
    While debugging the error I found that the json response formed in struts application as below.
    get json result in Jtable
     
    Hear the property names of jTable plugin are case sensitive. Only “Result”, “Records” and “Message” will work. In struts 2 the “json response” generated is in lower case[“result”, “records” and “message”], hence I edited the jtable.js to replace Result to result, Records to records and Message to message then it worked.
     
    **Note: Along with the above keyword replace TotalRecordCount to totalRecordCount respectively, since this parameter will be used to display pagination count(Which I will implement in upcoming tutorial)
     
    jquery-jtable-in-struts-2
     
    Now on including action for create, update and delete in jsp page as below

    actions : {
    	listAction : 'list',
    	createAction : 'create',
    	updateAction : 'update',
    	deleteAction : 'delete'
    }
    

     
    On running the application
    Integrating-jQuery-jTable-plugin-with-Struts2-framework
     
    On clicking ‘Add new record’
    Struts-2-using-jTable-jQuery-plug-in-Create-record
     
    On clicking edit button
    Struts-2-jTable-jQuery-plug-in-Update-record
     
    On clicking delete button
    Struts-2-jTable-jQuery-plug-in-Delete-record
     
    Note :
     
    In the above program I have not included the logic for create, delete and update functions. In the article CRUD Operations in Struts 2 using jTable jQuery plugin via Ajax I have implemented CRUD operation using jTable jQuery plugin in Struts 2, and in the article Pagination in Struts 2 using jQuery jTable plugin I have implemented paging feature using the same plugin.
     
    download
     

    Reference

     
    jTable official website
    AJAX based CRUD tables using ASP.NET MVC 3 and jTable jQuery plug-in
     

    Read More

    AJAX File Upload in Java Web Application using jQuery.AjaxFileUpload plugin

    Posted by in Ajax, J2EE, jQuery, Servlet | 3 comments

     
    ajax style file upload in servlet and jsp
     
    In my previous article on File Upload Example in Servlet & Jsp we learnt how to upload a file into sever via Apache Commons FileUpload plugin, In this article we shall add ajax style feature to our previous example using jQuery.AjaxFileUpload.js plugin.
     

    Modifications

     
    Before getting into the tutorial, I will let you know the small modification which I made in jQuery Form Plugin.
     
    1. By default this plugin allows only images, this is specified in jQuery.AjaxFileUpload.js as below.

    valid_extensions : ['gif','png','jpg','jpeg']
    

    So inorder to upload file with other extensions, I have modified this to

    valid_extensions : ['gif','png','jpg','jpeg','txt','docx','pdf','mkv']
    

    You can include/remove these extensions according to your requirement
     
    2. When file upload fails this plugin sends two parameter in response, they are
    status : Just has the status code, it is set to false when file upload fails
    message : This holds the error message.

    When file upload is successful, no response is sent back to client. So in order to send an upload success message I have modified the code from

    settings.onComplete.apply(element, [response, settings.params]);

    to

    settings.onComplete.apply(element, [ {
    	status : true,
    	message : 'Your file has been uploaded!'
    }, settings.params ]);
    

    Now let’s go ahead implement ajax file upload functionality in java web application
     

    Library

     

    Folder structure

     
    Now Create a dynamic web project in Eclipse with following folder structure
    Ajax file upload
     

    JSP

     

    <!DOCTYPE html>
    <html>
    <head>
    <title>Asynchronous file Upload in Java Web Application</title>
    <script src="jquery-1.8.2.js"></script>
    <script src="jQuery.AjaxFileUpload.js"></script>
    <script lang="Javascript">
    $(document).ready(function() {
      $('input[type="file"]').ajaxfileupload({
      'action' : 'UploadFile',
      'onComplete' : function(response) {
          $('#upload').hide();
          $('#message').show();
    			
          var statusVal = JSON.stringify(response.status);
    
         if(statusVal == "false")
         {
         $("#message").html("<font color='red'>"+JSON.stringify(response.message)+"</font>");
         }
         if(statusVal == "true")
         {
         $("#message").html("<font color='green'>"+JSON.stringify(response.message)+"</font>");
         }
    },
    'onStart' : function() {
    	$('#upload').show();
    	$('#message').hide();
    }
    });
    });
    </script>
    <style type="text/css">
    .centered {
    	width: 100%;
    	margin-left: auto;
    	margin-right: auto;
    	text-align: center;
    }
    </style>
    </head>
    <body>
    <form>
    <div class="centered">
    	<h4>AJAX Style File upload in Java Web Application</h4>
    	<input type="file" name="file" /><br />
    	<div id="upload" style="display: none;">Uploading..</div>
    	<div id="message"></div>
    </div>
    </form>
    </body>
    </html>
    

     
    The required jquery files are referenced in the head section of jsp file. Here whenever a file is selected, the script gets fired and triggers the servlet via action parameter, which holds the servlet url. This servlet in turn handles the file upload logic in the server side.
     
    Another must read:
    jQuery form validation using jQuery Validation plugin

    jQuery Tutorial for Beginners
     

    Servlet

     

    package com.fileupload;
    
    import java.io.File;
    import java.io.IOException;
    import java.util.List;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.FileItemFactory;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    
    public class UploadFile extends HttpServlet {
    	private static final long serialVersionUID = 1L;
    	private final String UPLOAD_DIRECTORY = "C:/Files";
    
    	protected void doPost(HttpServletRequest request,
                 HttpServletResponse response) throws ServletException, IOException {
    	boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    
    	// process only if it is multipart content
    	if (isMultipart) {
    		// Create a factory for disk-based file items
    		FileItemFactory factory = new DiskFileItemFactory();
    
    		// Create a new file upload handler
    		ServletFileUpload upload = new ServletFileUpload(factory);
    		try {
    		// Parse the request
    		List<FileItem> multiparts = upload.parseRequest(request);
    
    		for (FileItem item : multiparts) {
    		if (!item.isFormField()) {
    		String name = new File(item.getName()).getName();
    		item.write(new File(UPLOAD_DIRECTORY + File.separator + name));
    		}
    		}
    		}
    		catch (Exception e)
    		{
    		  e.printStackTrace();
    		}
    	}
    }
    }
    

     

    web.xml

     
    Make sure that the web.xml has following mappings

    <servlet>
    	<servlet-name>UploadFile</servlet-name>
    	<servlet-class>com.fileupload.UploadFile</servlet-class>
    </servlet>
    <servlet-mapping>
    	<servlet-name>UploadFile</servlet-name>
    	<url-pattern>/UploadFile</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    

     

    Demo

     
    On Running this application
    ajax file upload2
     
    When file upload is successful
    Ajax file upload6
     
    When we try to upload a file whose format is not specified in jQuery.AjaxFileUpload.js file
    Ajax file upload4
     
    I our next article we shall implement ajax file upload functionality with file upload progress bar.
     
    download
     

    Reference

     
    jQuery.AjaxFileUpload.js
     

    Read More
    Page 4 of 41234