Pages Navigation Menu

Coding is much easier than you think

CRUD Operations in Struts 2 using jTable jQuery plugin via Ajax

Posted by on Sep 20, 2014 in Ajax, jQuery, Struts-2 | 69 comments

 
Struts-2-jTable-jQuery-plug-in-Create-record-animation-effect
 
In the previous article “Setting up jQuery jTable plugin with Struts 2 framework” I have explained about how to setup jTable plugin in struts 2 application. This article describes on how to implement “Ajax based curd operation in Struts 2 using the JQuery jTable plugin, If you have not read the previous articles “Setting up jQuery jTable plugin with Struts 2 framework” I will recommend that you read that article first because it explains what jTable plugin is and how you can integrate it in Struts 2 application.
 

Steps done to set up our application for jTable

 
Libraries required for the setup,

 
Create a dynamic project in eclipse and setup above required libraries as explained here. The final project structure of this looks as below.
 
crud in struts 2 using jTable plugin
 
Setup from the browser perspective: jTable
 

JSP

 



jTable in Struts 2













AJAX based CRUD operation in Struts 2 using jTable plugin

 

JS file for implementing CRUD

 

$(document).ready(function() {
	$('#StudentTableContainer').jtable({
		title : 'Students List',
		actions : {
			listAction : 'listAction',
			createAction : 'createAction',
			updateAction : 'updateAction',
			deleteAction : 'deleteAction'
		},

		fields : {
			studentId : {
				title : 'Student Id',
				width : '30%',
				key : true,
				list : true,
				edit : false,
				create : true
			},
			name : {
				title : 'Name',
				width : '30%',
				edit : true
			},
			department : {
				title : 'Department',
				width : '30%',
				edit : true
			},
			emailId : {
				title : 'Email',
				width : '20%',
				edit : true
			}
		}
	});
	$('#StudentTableContainer').jtable('load');
});

 
I have explained the working of above jTable js file in my previous article “Setting up JQuery jTable plugin in Struts 2”, hence I’m not going to explain it again.
 
Now create a student table in Oracle database using the query below. On this table we are going to perform CRUD operation via ajax
 

create table Student(studentid int,name varchar(50),department varchar(50),
email varchar(50));

 

CurdDao

Create a class that performs CRUD operation in database
 

package com.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.jdbc.DataAccessObject;
import com.model.Student;

public class CrudDao {

private Connection dbConnection;
private PreparedStatement pStmt;

public CrudDao() {
	dbConnection = DataAccessObject.getConnection();
}

public void addStudent(Student student) {
	String insertQuery = "INSERT INTO STUDENT(STUDENTID, NAME, " +
			"DEPARTMENT, EMAIL) VALUES (?,?,?,?)";
	try {
		pStmt = dbConnection.prepareStatement(insertQuery);
		pStmt.setInt(1, student.getStudentId());
		pStmt.setString(2, student.getName());
		pStmt.setString(3, student.getDepartment());
		pStmt.setString(4, student.getEmailId());
		pStmt.executeUpdate();
	} catch (SQLException e) {
		System.err.println(e.getMessage());
	}
}

public void deleteStudent(int userId) {
	String deleteQuery = "DELETE FROM STUDENT WHERE STUDENTID = ?";
	try {
		pStmt = dbConnection.prepareStatement(deleteQuery);
		pStmt.setInt(1, userId);
		pStmt.executeUpdate();
	} catch (SQLException e) {
		System.err.println(e.getMessage());
	}
}

public void updateStudent(Student student)  {
	String updateQuery = "UPDATE STUDENT SET NAME = ?, " +
			"DEPARTMENT = ?, EMAIL = ? WHERE STUDENTID = ?";
	try {
		pStmt = dbConnection.prepareStatement(updateQuery);		
		pStmt.setString(1, student.getName());
		pStmt.setString(2, student.getDepartment());
		pStmt.setString(3, student.getEmailId());
		pStmt.setInt(4, student.getStudentId());
		pStmt.executeUpdate();

	} catch (SQLException e) {
		System.err.println(e.getMessage());
	}
}

public List getAllStudents() {
	List students = new ArrayList();

	String query = "SELECT * FROM STUDENT ORDER BY STUDENTID";
	try {
		Statement stmt = dbConnection.createStatement();
		ResultSet rs = stmt.executeQuery(query);
		while (rs.next()) {
			Student student = new Student();

			student.setStudentId(rs.getInt("STUDENTID"));
			student.setName(rs.getString("NAME"));
			student.setDepartment(rs.getString("DEPARTMENT"));
			student.setEmailId(rs.getString("EMAIL"));
			students.add(student);
		}
	} catch (SQLException e) {
		System.err.println(e.getMessage());
	}
	return students;
}
}

I hope the above code is self explanatory
 
Setup from the server’s perspective: Servlet
 
In Struts 2 Action class, I have defined 4 method- create, read, update and delete to perform CRUD operations. 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 in detail about how to use struts2-json-plugin.jar clearly, So if you are not aware of how struts2-json-plugin works, then please go thorough the above mentioned link.
 

Action class

 

package com.action;

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

import com.dao.CrudDao;
import com.model.Student;
import com.opensymphony.xwork2.Action;

public class JtableAction {
	
	private CrudDao dao = new CrudDao();

	private List records;
	private String result;
	private String message;
	private Student record;

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

	public String list() {
		try {
			// Fetch Data from Student Table
			records = dao.getAllStudents();
			result = "OK";
		} catch (Exception e) {
			result = "ERROR";
			message = e.getMessage();
			System.err.println(e.getMessage());
		}
		return Action.SUCCESS;
	}

	public String create() throws IOException {
		record = new Student();
		
		record.setStudentId(studentId);
		record.setName(name);
		record.setDepartment(department);
		record.setEmailId(emailId);
	
		try {
			// Create new record
			dao.addStudent(record);
			result = "OK";

		} catch (Exception e) {
			result = "ERROR";
			message = e.getMessage();
			System.err.println(e.getMessage());
		}
		return Action.SUCCESS;	
	}

	public String update() throws IOException {
		Student student = new Student();
		
		student.setStudentId(studentId);
		student.setName(name);
		student.setDepartment(department);
		student.setEmailId(emailId);
		
		try {
			// Update existing record
			dao.updateStudent(student);
			result = "OK";
		} catch (Exception e) {
			result = "ERROR";
			message = e.getMessage();
			System.err.println(e.getMessage());
		}
		return Action.SUCCESS;
	}

	public String delete() throws IOException {
		// Delete record
		try {
			dao.deleteStudent(studentId);
			result = "OK";
		} catch (Exception e) {
			result = "ERROR";
			message = e.getMessage();
			System.err.println(e.getMessage());
		}
		return Action.SUCCESS;
	}

	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;
	}
	public Student getRecord() {
		return record;
	}

	public void setRecord(Student record) {
		this.record = record;
	}

	public List getRecords() {
		return records;
	}

	public String getResult() {
		return result;
	}

	public String getMessage() {
		return message;
	}

	public void setRecords(List records) {
		this.records = records;
	}

	public void setResult(String result) {
		this.result = result;
	}

	public void setMessage(String message) {
		this.message = message;
	}
}

 
If you read my article on CRUD Operations in Java Web Applications using jTable jQuery plugin via Ajax then you might have noted once difference here, i.e. I have not created any request or response object in action class to get the student parameters, because those parameter from jsp file auto bounded to my struts 2 action, this is done via struts2-jquery-plugin. One only requirement for this parameter to be passed from jsp is, you have create the member variable for those parameter in action class along with getters and setters as in above file.
 

You might be interested to read:

  • GridView in struts 2
  • Ajax implementation in Struts 2 without jQuery plugin
  • Tab Style Login and Signup example using jQuery in Java web application
  •  
    I have explained in detail about difference response generated for create, read, update and delete operation in the article CRUD Operations in Java Web Applications using jTable jQuery plugin via Ajax, So please refer to this article mentioned above, if you are not aware of the different response created for CRUD operation in Jtable plugin.
     

    Jtable Issue related to Struts 2

     
    As mentioned in my previous article , 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, since this parameter will be used to display pagination count (Which I will implement in upcoming tutorial)

     

    Model class

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

    package com.model;
    
    public class Student {
    
    	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;
    	}
    }
    

     

    DAO Class

     
    Create utility class which connect to database Using Oracle JDBC driver

    package com.jdbc;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    
    public class DataAccessObject {
    private static Connection connection = null;
    
    public static Connection getConnection() {
    	if (connection != null)
    		return connection;
    	else {
    		// database URL
    		String dbUrl = "jdbc:oracle:thin:@localhost:1521:XE";
    		try 
    		{
    		Class.forName("oracle.jdbc.driver.OracleDriver");
    		// set the url, username and password for the database
    		connection = DriverManager.getConnection(dbUrl, "system", "admin");
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		return connection;
    	}
    	}
    }
    

     

    Struts.xml

     
    Make sure that you have the following mapping in struts.xml

    
    	
    		
    			/index.jsp
    		
    		
    			
    		
    	
    
    

     

    web.xml

     

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

     

    Demo

     
    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
     
    Now the new record will be added with fade out animation
    Struts-2-jTable-jQuery-plug-in-Create-record-animation-effect
     
    On clicking edit button
    Struts-2-jTable-jQuery-plug-in-Update-record
     
    On clicking delete button
    Struts-2-jTable-jQuery-plug-in-Delete-record
     
    In the next article Pagination in Struts 2 using jQuery jTable plugin I have implemented paging feature in the CRUD example.
     
    download

     

    Reference

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

    Read More

    Setup and Load Data in jQGrid using Servlets and JSP

    Posted by on Aug 27, 2014 in Ajax, jQuery | 18 comments

    JqGrid is an Ajax-enabled JavaScript control that provides solutions for representing and manipulating grid data on the web. Since the grid loads data at client side via Ajax call-backs, so it can be integrated with any server-side technology, including PHP, ASP and Java. JqGrid uses a jQuery Java Script Library and is written as plugin for that package.
     

    Library required

     
    JqGrid library
    Jquery UI theme
    google-gson-2.2.4.jar
     
    Now to start with demonstration of above topic, let us Create a Dynamic Web Project in Eclipse, with following project structure.
     
    JqGrid structure
     
    As show in the image download the required library mentioned and place it in jQGrid and gridJs 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: JqGrid
     
    jQGrid 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

     

    
    
    
    jqGird in Servlet
    
    
    
    
    
    
    
    
    
    
    
    
    
    	

     
    As you can see, jQGrid just needs a div and table element as HTML tags.
     
    You might be interested to read:

     

    JS File

     
    File : getJqGridData.js

    jQuery(document).ready(function() {
    	$("#list").jqGrid({
    		url : "GridServlet",
    		datatype : "json",
    		mtype : 'POST',
    		colNames : [ 'Id', 'FirstName', 'LastName', 'City', 'State' ],
    		colModel : [ {
    			name : 'id',
    			index : 'id',
    			width : 100
    		}, {
    			name : 'firstName',
    			index : 'firstName',
    			width : 150,
    			editable : true
    		}, {
    			name : 'lastName',
    			index : 'lastName',
    			width : 150,
    			editable : true
    		}, {
    			name : 'city',
    			index : 'city',
    			width : 100,
    			editable : true
    		}, {
    			name : 'state',
    			index : 'state',
    			width : 100,
    			editable : true
    		} ],
    		pager : '#pager',
    		rowNum : 10,
    		rowList : [ 10, 20, 30 ],
    		sortname : 'invid',
    		sortorder : 'desc',
    		viewrecords : true,
    		gridview : true,
    		caption : 'Data Report',
    		jsonReader : {
    			repeatitems : false,
    		},
    		editurl : "GridServlet"
    	});
    	jQuery("#list").jqGrid('navGrid', '#pager', {
    		edit : true,
    		add : true,
    		del : true,
    		search : true
    	});
    });
    

     
    Setup done from the server’s perspective: Servlet
     
    In Servlet, we are going to use a JSON library to convert Java objects(jqGridModels) to JSON strings that will be parsed by jQGrid plugin 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.
     

    Servlet

     

    package servlet;
    
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import model.JqGridModel;
    
    import com.google.gson.Gson;
    import com.google.gson.GsonBuilder;
    
    public class JqGridServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
    
    	protected void doPost(HttpServletRequest request,
    		    HttpServletResponse response) throws ServletException, IOException {
    
    		JqGridModel gridModel1 = new JqGridModel();
    		gridModel1.setId(1);
    		gridModel1.setFirstName("Mohaideen");
    		gridModel1.setLastName("Jamil");
    		gridModel1.setCity("Coimbatore");
    		gridModel1.setState("TamilNadu");
    
    		JqGridModel gridModel2 = new JqGridModel();
    		gridModel2.setId(2);
    		gridModel2.setFirstName("Ameerkhan");
    		gridModel2.setLastName("Saffar");
    		gridModel2.setCity("Thirunelveli");
    		gridModel2.setState("Tamilnadu");
    
    		List jqGridModels = new ArrayList<>();
    		jqGridModels.add(gridModel1);
    		jqGridModels.add(gridModel2);
    
    		Gson gson = new GsonBuilder().setPrettyPrinting().create();
    		String jsonArray = gson.toJson(jqGridModels);
    		jsonArray = "{\"page\":1,\"total\":\"2\",\"records\":"
    			+ jqGridModels.size() + ",\"rows\":" + jsonArray + "}";
    
    		System.out.println(jsonArray);
    
    		response.getWriter().print(jsonArray);
    	}
    }
    

     
    For jQGrid, page property represents current page number, and total represent total no pages, records represents Total number of records and rows represent the actual data. A sample return value from the above servlet is shown below
     
    {“page”:1,”total”:”2″,”records”:2,”rows”:[
    {
    “id”: 1,
    “firstName”: “Mohaideen”,
    “lastName”: “Jamil”,
    “city”: “Coimbatore”,
    “state”: “TamilNadu”
    },
    {
    “id”: 2,
    “firstName”: “Ameerkhan”,
    “lastName”: “Saffar”,
    “city”: “Thirunelveli”,
    “state”: “Tamilnadu”
    }
    ]}
     

    Model class

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

    package model;
    
    public class JqGridModel {
    
    	private int id;
    	private String firstName;
    	private String lastName;
    	private String city;
    	private String state;
    
    	public int getId() {
    		return id;
    	}
    
    	public String getFirstName() {
    		return firstName;
    	}
    
    	public String getLastName() {
    		return lastName;
    	}
    
    	public String getCity() {
    		return city;
    	}
    
    	public String getState() {
    		return state;
    	}
    
    	public void setId(int id) {
    		this.id = id;
    	}
    
    	public void setFirstName(String firstName) {
    		this.firstName = firstName;
    	}
    
    	public void setLastName(String lastName) {
    		this.lastName = lastName;
    	}
    
    	public void setCity(String city) {
    		this.city = city;
    	}
    
    	public void setState(String state) {
    		this.state = state;
    	}
    }
    

     

    web.xml

     
    Make sure that the web.xml has the following mapping.

    
    	GridServlet
    	servlet.JqGridServlet
    
    
    	GridServlet
    	/GridServlet
    
    
    	index.jsp
    
    

     

    Demo

     
    On running the application
    Demo JqGrid
     
    On clicking add icon
    jQGrid add
     
    On clicking edit icon
    eDit JqGrid
     
    ** Update — The below screenshot is the demo of pagination in java web application via ajax using using jQuery jTable plugin, this plugin has several inbuilt theme and lot may cool features like crud implementation via ajax, internalization etc, to know more about this plugin, please refer the article here.
     
    Pagination-Cover
     
    download
     

    Read More

    CRUD Operations in Java Web Applications using jTable jQuery plugin via Ajax

    Posted by on Aug 24, 2014 in Ajax, J2EE, jQuery, jTable, Servlet | 39 comments

     
    Struts-2-jTable-jQuery-plug-in-Create-record-animation-effect
     
    In the previous article “Setting up JQuery jTable plugin in Java Web Applications” I have explained how to setup jTable plugin in java web application. This article describes on how to implement “Ajax based curd operation in Java Web Applications using the JQuery jTable plugin and it will not explain how to setup jTable plugin in java web application. So If you have not read the previous articles “Setting up JQuery jTable plugin in Java Web Applications I will recommend that you read that article first because it explains how you can integrate the JTable plug-in with a J2EE application, this article will assume that the code for the integration of the jQuery JTable plug-in is implemented, and only the code required for implementing CRUD operation will be explained here.
     

    Steps done to set up our application for jTable

     
    Libraries required for the setup,

     
    Create a dynamic project in eclipse and setup above required libraries as explained here. The final project structure of this looks as below.
     
    Curd in jtable java web application
     
    Setup 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

     

    
    
    
    CRUD operations using jTable in J2EE
    
    
    
    
    
    
    
    
    
    
    
    
    

    AJAX based CRUD operations using jTable in J2ee

     

    JS File

     

    $(document).ready(function() {
    	$('#StudentTableContainer').jtable({
    		title : 'Students List',
    		actions : {
    			listAction : 'Controller?action=list',
    			createAction : 'Controller?action=create',
    			updateAction : 'Controller?action=update',
    			deleteAction : 'Controller?action=delete'
    		},
    		fields : {
    			studentId : {
    				title : 'Student Id',
    				width : '30%',
    				key : true,
    				list : true,
    				edit : false,
    				create : true
    			},
    			name : {
    				title : 'Name',
    				width : '30%',
    				edit : true
    			},
    			department : {
    				title : 'Department',
    				width : '30%',
    				edit : true
    			},
    			emailId : {
    				title : 'Email',
    				width : '20%',
    				edit : true
    			}
    		}
    	});
    	$('#StudentTableContainer').jtable('load');
    });
    

     
    I have explained the working of above jTable js file in my previous article “Setting up JQuery jTable plugin in Java Web Applications”
     
    Now create a student table in Oracle database using the query below. On this table we are going to perform CRUD operation via ajax
     

    create table Student(studentid int,name varchar(50),department varchar(50),
    email varchar(50));
    

     

    CurdDao

    Create a class that performs CRUD operation in database
     

    package com.dao;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.ArrayList;
    import java.util.List;
    
    import com.jdbc.DataAccessObject;
    import com.model.Student;
    
    public class CrudDao {
    
    private Connection dbConnection;
    private PreparedStatement pStmt;
    
    public CrudDao() {
    	dbConnection = DataAccessObject.getConnection();
    }
    
    public void addStudent(Student student) {
    	String insertQuery = "INSERT INTO STUDENT(STUDENTID, NAME, " +
    			"DEPARTMENT, EMAIL) VALUES (?,?,?,?)";
    	try {
    		pStmt = dbConnection.prepareStatement(insertQuery);
    		pStmt.setInt(1, student.getStudentId());
    		pStmt.setString(2, student.getName());
    		pStmt.setString(3, student.getDepartment());
    		pStmt.setString(4, student.getEmailId());
    		pStmt.executeUpdate();
    	} catch (SQLException e) {
    		System.err.println(e.getMessage());
    	}
    }
    
    public void deleteStudent(int userId) {
    	String deleteQuery = "DELETE FROM STUDENT WHERE STUDENTID = ?";
    	try {
    		pStmt = dbConnection.prepareStatement(deleteQuery);
    		pStmt.setInt(1, userId);
    		pStmt.executeUpdate();
    	} catch (SQLException e) {
    		System.err.println(e.getMessage());
    	}
    }
    
    public void updateStudent(Student student)  {
    	String updateQuery = "UPDATE STUDENT SET NAME = ?, " +
    			"DEPARTMENT = ?, EMAIL = ? WHERE STUDENTID = ?";
    	try {
    		pStmt = dbConnection.prepareStatement(updateQuery);		
    		pStmt.setString(1, student.getName());
    		pStmt.setString(2, student.getDepartment());
    		pStmt.setString(3, student.getEmailId());
    		pStmt.setInt(4, student.getStudentId());
    		pStmt.executeUpdate();
    
    	} catch (SQLException e) {
    		System.err.println(e.getMessage());
    	}
    }
    
    public List getAllStudents() {
    	List students = new ArrayList();
    
    	String query = "SELECT * FROM STUDENT ORDER BY STUDENTID";
    	try {
    		Statement stmt = dbConnection.createStatement();
    		ResultSet rs = stmt.executeQuery(query);
    		while (rs.next()) {
    			Student student = new Student();
    
    			student.setStudentId(rs.getInt("STUDENTID"));
    			student.setName(rs.getString("NAME"));
    			student.setDepartment(rs.getString("DEPARTMENT"));
    			student.setEmailId(rs.getString("EMAIL"));
    			students.add(student);
    		}
    	} catch (SQLException e) {
    		System.err.println(e.getMessage());
    	}
    	return students;
    }
    }
    

    I hope the above code is self explanatory
     
    Setup from the server’s perspective: Servlet
     
    jTable uses the POST method by default while making AJAX calls to the server and in server side, we will convert Java objects created under different CRUD operation to JSON strings that will be parsed by jTable pugin in the JSP page and will be rendered on the web page. This conversion of Java Object to Json format is done using Google gson jar. I have used the below method of gson library to convert java object to json object
     

    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String jsonArray = gson.toJson(JSONROOT);
    

     
    Now let us look into the different response created for CRUD operations
     

    Reading

     
    Method to jTable to get a list of records:
     

    HashMap JSONROOT = new HashMap();
    
    if (action.equals("list")) {
    try{
    	// Fetch Data from Student Table
    	studentList = dao.getAllStudents();
    
    	// 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);
    
    	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);
    }
    }
    

     
    For read operations, 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 to show in the MySql table. 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”: “Muthu vijay”,
    “department”: “CSE”,
    “emailId”: “muthu@xyz.com”
    },
    {
    “studentId”: 2,
    “name”: “Bashit”,
    “department”: “EEE”,
    “emailId”: “xyz@abc.com”
    },
    {
    “studentId”: 3,
    “name”: “Haripriya”,
    “department”: “IT”,
    “emailId”: “hp@abc.com”
    }
    ]}
     

    Creating & Updating

     
    Creating and Updating a record is optional. If you allow user to create/update a record, you must supply an action to jTable to create a new record. In case of create you must return the newly created object in JSON format, where as in case of update you must return the updated object via its respective action, which is done via gson library. A sample return value for createAction/UpdateAction is shown below
     
    {“Result”:”OK”,”Record”:{
    “studentId”: 9,
    “name”: “Lahir nisha”,
    “department”: “CSE”,
    “emailId”: “lahir@abc.com”
    }}
     

    if (action.equals("create") || action.equals("update")) {
    try{
    	Student student = new Student();
    	if (request.getParameter("studentId") != null) {
    		int studentId = Integer.parseInt(request.getParameter("studentId"));
    		student.setStudentId(studentId);
    	}
    
    	if (request.getParameter("name") != null) {
    		String name = request.getParameter("name");
    		student.setName(name);
    	}
    
    	if (request.getParameter("department") != null) {
    		String department = request.getParameter("department");
    		student.setDepartment(department);
    	}
    
    	if (request.getParameter("emailId") != null) {
    		String emailId = request.getParameter("emailId");
    		student.setEmailId(emailId);
    	}
    
    	if (action.equals("create")) {
    		// Create new record
    		dao.addStudent(student);
    	} else if (action.equals("update")) {
    		// Update existing record
    		dao.updateStudent(student);
    	}
    
    	// Return in the format required by jTable plugin
    	JSONROOT.put("Result", "OK");
    	JSONROOT.put("Record", student);
    
    	// Convert Java Object to Json
    	String jsonArray = gson.toJson(JSONROOT);
    	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);
    }
    }
    

     

    Deleting

     
    Similar to update/create option, delete record is optional. If you allow user to delete a record, you must supply an action to jTable to delete a record, and response of delete operation is similar to update.
     

    if (action.equals("delete")) {
    try{
    	// Delete record
    	if (request.getParameter("studentId") != null) {
    		int studentId = Integer.parseInt(request.getParameter("studentId"));
    		dao.deleteStudent(studentId);
    
    		// Return in the format required by jTable plugin
    		JSONROOT.put("Result", "OK");
    
    		// Convert Java Object to Json
    		String jsonArray = gson.toJson(JSONROOT);
    		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);
    }
    }
    

     

    Model class

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

    package com.model;
    
    public class Student {
    
    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;
    }
    }
    

     

    DAO Class

     
    Create utility class which connect to database Using Oracle JDBC driver

    package com.jdbc;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    
    public class DataAccessObject {
    	private static Connection connection = null;
    
    	public static Connection getConnection() {
    		if (connection != null)
    			return connection;
    		else {
    			// Store the database URL in a string
    		String serverName = "127.0.0.1";
    		String portNumber = "1521";
    		String sid = "XE";
    		String dbUrl = "jdbc:oracle:thin:@" + serverName + ":" + portNumber
    				+ ":" + sid;
    		try {
    		Class.forName("oracle.jdbc.driver.OracleDriver");
    		// set the url, username and password for the database
    		connection = DriverManager.getConnection(dbUrl, "system", "admin");
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		return connection;
    	}
    	}
    }
    

     

    web.xml

     

    
      index.jsp
    
    
      Controller
      com.servlet.Controller
    
    
      Controller
      /Controller
    
    

     

    Demo

     
    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
     
    Now the new record will be added with fade out animation
    Struts-2-jTable-jQuery-plug-in-Create-record-animation-effect
     
    On clicking edit button
    Struts-2-jTable-jQuery-plug-in-Update-record
     
    On clicking delete button
    Struts-2-jTable-jQuery-plug-in-Delete-record
     
    In the next article Pagination in Java Web Applications using jQuery jTable plugin I have implemented paging feature to the CRUD example demonstrated here.
     
    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 Struts2 using jQuery DataTable via Ajax

    Posted by on May 31, 2014 in Ajax, jQuery, Struts-2 | 17 comments

     
    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

    Read More

    Ajax File Upload with Progress Bar using jQuery in Java web application

    Posted by on May 29, 2014 in Ajax, J2EE, jQuery, Servlet | 11 comments

    In my previous article we learnt on how to implement AJAX Style file upload in a java web application. In this post we shall learn on how to create AJAX file uploading system with progress bar which shows upload progress in percentage (%) using jQuery in java web application. I have used jQuery Form plugin for this purpose. This plugin is easy to use and supports iframe file transportation.
     
    Ajax File Upload with Progress Bar2
     

    Libraries required for the setup

     

    Folder structure

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

    Set up from browser perspective: jQuery

     
    Jsp form which handles file uploads
     

    
    
    
    Ajax File Upload with Progress Bar
    
    
    
    
    
    
    
    
    

    Ajax File Upload with Progress Bar

    0%

     
    The JQuery code written on the head section of the jsp page is responsible for the AJAX call made to the servlet, which in turn uploads file into server.
     

    Js file

     
    Shown below is the jQuery code for upload file and progress bar
     

    $(document).ready(function() {
    var options = {
    	beforeSend : function() {
    		$("#progressbox").show();
    		// clear everything
    		$("#progressbar").width('0%');
    		$("#message").empty();
    		$("#percent").html("0%");
    	},
    	uploadProgress : function(event, position, total, percentComplete) {
    		$("#progressbar").width(percentComplete + '%');
    		$("#percent").html(percentComplete + '%');
    
    		// change message text to red after 50%
    		if (percentComplete > 50) {
    		$("#message").html("File Upload is in progress");
    		}
    	},
    	success : function() {
    		$("#progressbar").width('100%');
    		$("#percent").html('100%');
    	},
    	complete : function(response) {
    	$("#message").html("Your file has been uploaded!");
    	},
    	error : function() {
    	$("#message").html(" ERROR: unable to upload files");
    	}
    };
    $("#UploadForm").ajaxForm(options);
    });
    

     
    beforeSend : this function called before form submission
    uploadProgress : this function called when the upload is in progress
    success : this function is called when the form upload is successful.
    complete: this function is called when the form upload is completed.
     
    Another must read:
    jQuery form validation using jQuery Validation plugin

    jQuery Tutorial for Beginners
     

    Setup from the server’s perspective: 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 its 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 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) 
    		{
    		  System.out.println("File upload failed");
    		}
    	}
    }
    }
    

     

    Demo

     
    Ajax File Upload with Progress Bar
     
    download
     

    Read More