Pages Navigation Menu

Coding is much easier than you think

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

Posted by in Ajax, J2EE, jQuery, jTable, Servlet

 
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 pagination in Java web application using jTable 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

 

<html>
<head>
<title>CRUD operations using jTable in J2EE</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>
<!-- User Defined Jtable js file -->
<script src="js/userDefieneJTableJs.js" type="text/javascript"></script>

</head>
<body>
<div style="text-align: center;">
	<h4>AJAX based CRUD operations using jTable in J2ee</h4>
	<div id="StudentTableContainer"></div>
</div>
</body>
</html>

 

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”, 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<Student> getAllStudents() {
	List<Student> students = new ArrayList<Student>();

	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(studentList);

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

Reading

 
Method to jTable to get a list of records:
 

if (action.equals("list")) {
try {
	// Fetch Data from Student Table
	studentList = dao.getAllStudents();
	// Convert Java Object to Json
	String jsonArray = gson.toJson(studentList);

	// Return Json in the format required by jTable plugin
	jsonArray = "{\"Result\":\"OK\",\"Records\":"+ jsonArray + "}";
	response.getWriter().print(jsonArray);
	} catch (Exception e) {
		String error = "{\"Result\":\"ERROR\",\"Message\":" + e.getMessage()+ "}";
		response.getWriter().print(error);
		System.err.println(e.getMessage());
	}
}
catch (Exception e) {
	String error = "{\"Result\":\"ERROR\",\"Message\":"
		+ "Exception on listing records }";
	response.getWriter().print(error);
	System.err.println(e.getMessage());
	}
}

 
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": "[email protected]"
},
{
"studentId": 2,
"name": "Bashit",
"department": "EEE",
"emailId": "[email protected]"
},
{
"studentId": 3,
"name": "Haripriya",
"department": "IT",
"emailId": "[email protected]"
}
]}
 

Creating

 
Creating a record is optional. If you allow user to create a record, you must supply an action to jTable to create a new record. This method must return the newly created object in JSON format, which is done via gson library. A sample return value for createAction is shown below
 
{“Result”:”OK”,”Record”:{
“studentId”: 9,
“name”: “Lahir nisha”,
“department”: “CSE”,
“emailId”: “[email protected]
}}
 

if (action.equals("create")) {
		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);
		}

		try {
			// Create new record
			dao.addStudent(student);
			// Convert Java Object to Json
			String json = gson.toJson(student);
			// Return Json in the format required by jTable plugin
			String jsonData = "{\"Result\":\"OK\",\"Record\":"+ json + "}";
			response.getWriter().print(jsonData);
		} catch (Exception e) {
			String error = "{\"Result\":\"ERROR\",\"Message\":" + e.getMessage()+ "}";
			response.getWriter().print(error);
		}
}

 

Updating

 
Update a record is optional. If you allow user to edit (update) a record, then you must supply an action to jTable to update a record, here if update option is successful, then, Result property must be “OK”. If error then Result property must be “ERROR”.
 

if (action.equals("update")) {
		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);
		}

		try {
			// Update existing record
			dao.updateStudent(student);
			// Convert Java Object to Json
			String json = gson.toJson(student);
			String jsonData = "{\"Result\":\"OK\",\"Record\":" + json + "}";
			response.getWriter().print(jsonData);
		} catch (Exception e) {
			String error = "{\"Result\":\"ERROR\",\"Message\":" + e.getMessage()+ "}";
			response.getWriter().print(error);
		}
	}

 

Deleting

 
Similar to update 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);
			String jsonData = "{\"Result\":\"OK\"}";
			response.getWriter().print(jsonData);
		}
	} catch (Exception e) {
		String error = "{\"Result\":\"ERROR\",\"Message\":" + e.getMessage()+ "}";
		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

 

<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

 
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.
 

dwd2
Download It – AjaxjTableServlet.war

 

Reference

 
http://www.codeproject.com/Articles/277576/AJAX-based-CRUD-tables-using-ASP-NET-MVC-and-jTa

Read More

Dynamic Dependent Select Box in JSP & Servlet using JQuery and JSON via Ajax

Posted by in Ajax, J2EE, jQuery, Servlet

 
Dynamic Dependent Select Box using Jquery
 
In my previous post, I explained about making AJAX calls from JSP page to servlet and updating a part of the JSP page with the response of simple java object from the Servlet. In this post we shall make the servlet to return complex Java Objects such as lists, maps, etc with the help of JSON and JQuery.
 

Library required

 
Google’s gson
 

Steps done to set up our Servlet for JSON

 
From the browser perspective: jQuery

jQuery allows you to issue an ajax request via get or post method and expects a JSON object as a response, as described in my previous post the first and second parameter of these method are the url and a key-value pair and the third argument of get method is a function that defines what is to be done with the response that is got back from the Servlet.
 

Recommended reading:

  • AJAX implementation in Java web application using JQuery
  • Ajax implementation without jQuery library
  •  

    Jsp Page

     
    Now, let us create a JSP page with two drop down lists, one contains values for sports and the other that is going to be populated with values for players based on the value selected in the first drop down list. This is done without page refresh, by making AJAX calls to the Servlet on first drop down list change event.
     

    <html>
    <head>
    <title>AJAX in Servlet using JQuery and JSON</title>
    <script src="js/jquery-1.11.1.js" type="text/javascript"></script>
    
    <script>
    $(document).ready(function() {
    	$('#sports').change(function(event) {
    		var sports = $("select#sports").val();
    		$.get('JsonServlet', {
    			sportsName : sports
    		}, function(jsonResponse) {
    			var select = $('#player');
    			select.find('option').remove();
    			$.each(jsonResponse, function(key, value) {
    				$('<option>').val(key).text(value).appendTo(select);
    			});
    		});
    	});
    });
    </script>
    </head>
    <body>
    <h3>AJAX in Servlet using JQuery and JSON</h3>
    	Select Favorite Sports:
    	<select id="sports">
    		<option>Select Sports</option>
    		<option value="Football">Football</option>
    		<option value="Cricket">Cricket</option>
    	</select>
    	<br /> <br />
    	Select Favorite Player:
    	<select id="player">
    		<option>Select Player</option>
    	</select>
    </body>
    </html>
    

     

    Also read:

     
    From the server’s perspective: Servlet

    In Servlet, we are going to use a GSON library to convert Java objects (lists, maps etc) to JSON strings that will be parsed by JQuery in the JSP page and will be displayed on the web page.
     

    Servlet

     

    package com.action;
    
    import java.io.IOException;
    import java.util.*;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import com.google.gson.Gson;
    
    public class JsonServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
    
    	protected void doGet(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    
    		String sportsName = request.getParameter("sportsName");
    		Map<String, String> playerMap = new LinkedHashMap<String, String>();
    		String json = null;
    		
    		if (sportsName.equals("Football")) {
    			playerMap.put("1", "Lionel Messi");
    			playerMap.put("2", "Cristiano Ronaldo");
    			playerMap.put("3", "David Beckham");
    			playerMap.put("4", "Diego Maradona");
    		} else if (sportsName.equals("Cricket")) {
    			playerMap.put("1", "Sourav Ganguly");
    			playerMap.put("2", "Sachin Tendulkar");
    			playerMap.put("3", "Lance Klusener");
    			playerMap.put("4", "Michael Bevan");
    		} else if (sportsName.equals("Select Sports")) {
    			playerMap.put("1", "Select Player");
    		}
    
    		json = new Gson().toJson(playerMap);
    		response.setContentType("application/json");
    		response.getWriter().write(json);
    	}
    }
    

     
    In the above code, we create a map(playerMap) and populates its value based on the sportsName parameter passed to the Servlet in the AJAX call made by the JQuery’s get() method. This map object is converted to json strings and the response is sent back to the JSP page.
     

    Web.xml

    Servlet mapping should be done in web.xml as shown below
     

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

     

    Demo

     
    On selecting ‘Football’ in the first dropdown list
     
    Dynamic Dependent Select Box in JSP
     
    On selecting ‘Cricket’ in the first dropdown list
     
    Dynamic Dependent Select Box in JSP2
     

    dwd2
    Download It – JqueryJsonServlet.war

      Read More

    AJAX implementation in Struts 2 using JQuery and JSON

    Posted by in Ajax, jQuery, Struts-2 | 15 comments

     
    Dynamic Dependent Select Box using Jquery in struts2
     
    In this post, we will learn to implement AJAX calls from a JSP page to a Struts 2 Action class using JQuery and update the same JSP page back with the Json response from the Struts 2.
     

    Library required

     
    Since the response to be sent to jQuery is of type JSON, 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.
     

    Steps done to set up our action for JSON

     
    From the browser perspective: jQuery

    jQuery allows you to issue an ajax request and expects a JSON object as a response.
     

    Jsp Page

     
    Now, let us create a JSP page with two drop down lists, one contains values for countries and the other that is going to be populated with values for states based on the value selected in the first drop down list. This is done without a page refresh, by making AJAX calls to the Struts 2 action on first drop down list change event.
     
    Recommended reading :

  • AJAX implementation in Struts 2 without JQuery
  •  

    <%@ taglib prefix="s" uri="/struts-tags"%>
    <html>
    <head>
    <title>AJAX in Struts 2 using JSON and jQuery</title>
    <script src="js/jquery-1.8.2.js" type="text/javascript"></script>
    <script>
    $(document).ready(function() {
       $('#country').change(function(event) {
          var country = $("select#country").val();
          $.getJSON('ajaxAction', {
    	countryName : country
          }, function(jsonResponse) {
    	$('#ajaxResponse').text(jsonResponse.dummyMsg);
    	var select = $('#states');
    	select.find('option').remove();
    	$.each(jsonResponse.stateMap, function(key, value) {
    	  $('<option>').val(key).text(value).appendTo(select);
    	});
          });
          });
    });
    </script>
    </head>
    <body>
       <h3>AJAX calls to Struts 2 using JSON and jQuery</h3>
       <s:select id="country" name="country"
    	list="{'Select Country','India','US'}" label="Select Country" />
       <br />
       <br />
       <s:select id="states" name="states" list="{'Select State'}"
    	label="Select State" />
       <br />
       <br />
       <div id="ajaxResponse"></div>
    </body>
    </html>
    

     
    Note that I have referenced jQuery files in the head section of the jsp which is responsible for the AJAX call made to the struts 2 action and for displaying the response back in the JSP.
     
    Whenever the value is selected in the “country” drop down list, its change event is fired and the ‘getJSON’ function executes ajaxAction (first argument of ‘getJSON’) configured in struts.xml. I have explained about the parameters of ‘getJSON’ method in the article here.
     
    From the server’s perspective: Struts 2
     
    In action class you need to create instance variables and its respective getter and setter methods. Here all the variables that have a setter can be set to the values received as parameters from jQuery and all the variables that have a getter method can be retrieved in the client javascript code.
     
    Also read :

  • GridView in struts 2 using jQuery DataTable plugin
  • CRUD Operations in Struts 2 using jTable jQuery plugin via Ajax
  • Autocomplete in Java web application using jQuery
  • Tab Style Login and Signup example using jQuery in Java web application
  •  

    Action class

     

    package com.action;
    
    import java.util.LinkedHashMap;
    import java.util.Map;
    
    import com.opensymphony.xwork2.Action;
    
    public class AjaxJsonAction implements Action{
    
    private Map<String, String> stateMap = new LinkedHashMap<String, String>();
    private String dummyMsg;
    //Parameter from Jquery
    private String countryName;
    
    public String execute() {
    	if (countryName.equals("India")) {
    		stateMap.put("1", "Kerala");
    		stateMap.put("2", "Tamil Nadu");
    		stateMap.put("3", "Jammu Kashmir");
    		stateMap.put("4", "Assam");
    	} else if (countryName.equals("US")) {
    		stateMap.put("1", "Georgia");
    		stateMap.put("2", "Utah");
    		stateMap.put("3", "Texas");
    		stateMap.put("4", "New Jersey");
    	} else if (countryName.equals("Select Country")) {
    		stateMap.put("1", "Select State");
    	}
    	dummyMsg = "Ajax action Triggered";
    	return SUCCESS;
    }
    
    public Map<String, String> getStateMap() {
    	return stateMap;
    }
    
    public String getDummyMsg() {
    	return dummyMsg;
    }
    
    public String getCountryName() {
    	return countryName;
    }
    
    public void setStateMap(Map<String, String> stateMap) {
    	this.stateMap = stateMap;
    }
    
    public void setDummyMsg(String dummyMsg) {
    	this.dummyMsg = dummyMsg;
    }
    
    public void setCountryName(String countryName) {
    	this.countryName = countryName;
    }
    }
    

     
    In the above code, we create a maps and populates its value based on the country parameter passed to the action class by the AJAX call made by the JQuery’s getJSON() method.
     

    struts.xml

     
    Since the response needed by jQuery is of type json, so we need to convert this map objects to json strings, for this you need to configure this Action class in struts.xml such that it returns a json object. This configuration is as follows:

    Create a package in struts.xml file, which extend json-default and specify the result type of your action class inside this package to be json. The json-default package contains an interceptor and the result type configuration for JSON requests and responses.

    <struts>
    <package name="default" extends="json-default">
       <action name="ajaxAction" class="com.action.AjaxJsonAction">
    	<result type="json">/index.jsp</result>
       </action>
    </package>
    </struts>
    

     
    Note: json-default package extends struts-default

    Please read the Struts 2 JSON plugin documentation for more details.

     

    Web.xml

     

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

     

    Demo

     
    On selecting ‘India’ in the first dropdown list
     
    Struts2_ajax_json_jquery
     
    On selecting ‘US’ in the first dropdown list
     
    Struts2_ajax_json_jquery _2
     

    dwd2
    Download It – JqueryJsonStruts2.war

      Read More

    AJAX in Java web application using JQuery

    Posted by in J2EE, Java, jQuery

     
    jQuery-Ajax-Servlet-Jsp
     
    In this post, we will learn to implement AJAX calls from a JSP page to a Servlet and display the servlets response back in the JSP using Jquery without page refresh. Please make a Google search about Ajax to if you are not aware of the same. Now to start with demonstration of above topic, let us create a Dynamic Web Project in Eclipse, with following project structure.
     
    jquery ajax basic
     
    As show 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 using Jquery in Servlet</title>
    <script src="js/jquery-1.11.1.js" type="text/javascript"></script>
    <script>
    	$(document).ready(function() {
    		$('#submit').click(function(event) {
    			var name = $('#userName').val();
    			$.get('JqueryServlet', {
    				userName : name
    			}, function(responseText) {
    				$('#ajaxResponse').text(responseText);
    			});
    		});
    	});
    </script>
    </head>
    <body>
    <form>
    	<fieldset>
    	<legend>AJAX implementation in JSP and Servlet using JQuery</legend>
    		<br/>
    		Enter your Name: <input type="text" id="userName" />
    		<input type="button" id="submit" value="Ajax Submit" />
    	</fieldset>
    		 <br /> <br />
    	<fieldset>
    		<legend>Response from jQuery Ajax Request</legend>
    		<br/>
    		<div id="ajaxResponse"></div>
    	</fieldset>
    
    </form>
    </body>
    </html>
    

     
    Here when the user clicks on “Ajax Submit” button, its click event is fired and the ‘get’ function executes the Ajax GET request on the Servlet. 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.
     

    Recommended reading:

  • Ajax implementation without jQuery library
  •  

    Servlet

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

    package com.simplecodestuffs.ajax;
    
    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.
     

    Also read:

  • Autocomplete in Java web application using jQuery
  • Dynamic dependent dropdown in Java web application using jQuery
  • Tab Style Login and Signup example using jQuery in Java web application
  •  

    Web.xml

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

    <?xml version="1.0" encoding="UTF-8"?>
    <welcome-file-list>
       <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <servlet>
       <servlet-name>JqueryServlet</servlet-name>
    <servlet-class>com.simplecodestuffs.ajax.JqueryServlet</servlet-class>
    </servlet>
    <servlet-mapping>
       <servlet-name>JqueryServlet</servlet-name>
       <url-pattern>/JqueryServlet/*</url-pattern>
    </servlet-mapping>
    

     

    Demo

     
    AJAX implementation in JSP and Servlet using JQuery

    On running the application the above webpage is generated, in which enter a value and click “Ajax Submit” button, then you will see a welcome message saying “Hello (userName)”.

    Note: Inorder to return complex Java objects such as list, map, etc. as response you can use JSON. In the article here I have implemented the same.
     

    dwd2
    Download It – JqueryAjaxServlet.war

      Read More

    Setting up jQuery jTable plugin in Servlets and JSP

    Posted by in J2EE, Java, jQuery, jTable

     
    In this article we will learn to setup jTable and dependent libraries in a Java web application(using Servlets and JSP’s)
     
    Integrating jQuery jTable plugin with Struts2 framework
     
    As per the definition in jTable.org, jTable is a jQuery plugin which is used to create AJAX based CRUD tables without coding HTML or Javascript. jTable takes a div id and automatically generates the html table inside the div and it uses jQuery UI dialog that pops up when the user clicks on add, edit or update record buttons and it has several pre-defined color themes . In this example I have used metro blue theme for my project.

    To know more on jTable plugin please read on its official home page.
     

    Steps done to set up our application for jTable

     
    Libraries required
    jquery plugin

     
    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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>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 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.
     
    In the jsp above I have only provided action url for listAction for demonstration purpose. 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.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;
    
        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]"));
    
    		// Convert Java Object to Json
    		String jsonArray = gson.toJson(studentList);
    
    		//Return Json in the format required by jTable plugin
    		jsonArray="{\"Result\":\"OK\",\"Records\":"+jsonArray+"}";
    		System.out.println(jsonArray);
    		response.getWriter().print(jsonArray);
    		}
    		catch(Exception ex){
    			String error="{\"Result\":\"ERROR\",\"Message\":"+ex.getMessage()+"}";
    			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'
    }
    

     
    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 Java Web Applications using jTable jQuery plugin via Ajax I have implemented CRUD operation using jTable jQuery plugin in J2EE, and in the article Pagination in Java Web Applications using jQuery jTable plugin I have implemented paging feature using the same plugin.
     

    dwd2
    Download It – jTableInServlet

     

    Reference

     
    http://jtable.org/ApiReference
     

    Read More
    Page 3 of 4112345...102030...Last»