Pages Navigation Menu

Coding is much easier than you think

AngularJS Interacting with Java Servlet using JSON

Posted by on Apr 26, 2015 in Ajax, AngularJS, Servlet | 5 comments

Angular2
 
In this post, I am going to demonstrate a simple example on how to make AJAX calls from a JSP page to a Servlet using AngularJS and update the same JSP page back with the JSON response from the Servlet. In other words, this post will give you an overview on how to integrate AngularJS in a Java web applications.
 
There are many JSON libraries available that can be used to pass AJAX updates between the server and the client. I am going to use google’s gson library in this example.
 
Below are the steps to reproduce to create a simple AngularJS enabled Java Web Application using Eclipse and Tomcat 7,
 

How to use?

 
First of all create a “Dynamic Web Project” in Eclipse and download the AngularJS library and place in js folder of eclipse work-space, and refer this files in the head section in the jsp, this file is responsible for the AJAX call made to the servlet and for updating the response back in the JSP.
 

Jsp Page

 

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>AJAX with Servlets using AngularJS</title>
<script type="text/javascript" src="js/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);

function MyController($scope, $http) {

	$scope.getDataFromServer = function() {
		$http({
			method : 'GET',
			url : 'javaAngularJS'
		}).success(function(data, status, headers, config) {
			$scope.person = data;
		}).error(function(data, status, headers, config) {
			// called asynchronously if an error occurs
			// or server returns response with an error status.
		});

	};
};
</script>
</head>
<body>
<div ng-app="myApp">
	<div ng-controller="MyController">
  	   <button ng-click="getDataFromServer()">Fetch data from server</button>
	   <p>First Name : {{person.firstName}}</p>
	   <p>Last Name : {{person.lastName}}</p>
	</div>
</div>
</body>
</html>

 

HTML – Data Binding

 
We can display JSON data values in jsp by using their attributes in expressions like {{person.firstName}}, {{person.lastName}} etc.. Here the id=”ng-app” is most important for Internet Explorer browser data binding.
 
ng-controller
Specifies a JavaScript controller class that evaluates HTML expressions.

ng-click
Angular on click event
 

Model class

 

package com.model;

public class PersonData {

	private String firstName;
	private String lastName;

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

}

 
Recommended Reading:

 

Servlet

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

package com.controller;

import java.io.IOException;

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.model.PersonData;

public class AngularJsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public AngularJsServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request,
	    HttpServletResponse response) throws ServletException, IOException {
		PersonData personData = new PersonData();
		personData.setFirstName("Mohaideen");
		personData.setLastName("Jamil");

		String json = new Gson().toJson(personData);
		response.setContentType("application/json");
		response.getWriter().write(json);
	}
}

 

Code Explanation

 
When the user clicks on “Fetch data from server” button, button click event is fired via angularJS “ng-click” directive and the ‘http’ function executes the Ajax GET request on the Servlet.
 

Web.xml

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

<web-app>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>javaAngularJS</servlet-name>
    <servlet-class>com.controller.AngularJsServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>javaAngularJS</servlet-name>
    <url-pattern>/javaAngularJS</url-pattern>
  </servlet-mapping>
</web-app>

 

Demo

 
Once you done with above steps then Right click on project –> Run As –> Run on Server
(Note: I have used tomcat server to run this application. If you are not sure how to configure tomcat server in eclipse please follow this link).
 
AngularJS demo1
 
Click button: Fetch data from server to pass HTTP request using angularJS where Java servlet will return data as below:

AngularJS demo

download
 

Reference

 
AngularJS API Docs

Read More

Ajax Cascading DropDownList in JSP & Servlet using JQuery and JSON

Posted by on Apr 12, 2015 in Ajax, jQuery, Servlet | 5 comments

 
Dynamic Dependent Select Box using Jquery
 
There are times in a web application where you want to populate a dropdown list based on the value of another drop down list. In this example, we will be creating a dropdown list for favorite spots and favorite player; since this scenario involves in returning complex java objects like lists, maps, etc, so I’m using JSON for this purpose.

In the article on AJAX in Servlet & jsp using JQuery I have demonstrated on returning simple object from servlet to jsp via jquery.

 

Library required

 
Google gson
 

Project Structure

 
Ajax using jquery and json
 

Steps done to set up our Servlet for JSON

 
From the browser perspective: jQuery

jQuery allows you to fire 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:

 

Jsp Page

 

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

	var select = $('#player');
	select.find('option').remove();
 	  $.each(response, function(index, value) {
	  $('<option>').val(value).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>

 
Here jquery will fire an ajax request when the value of the first dropdown is changed(id=”sports”).
 

Another must read:

 
From the server’s perspective: Servlet

In Servlet, I’m 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 and note that I have returned the response back to jsp based on the value of sports parameter which i pass to the servlet via jQuery’s get() method.
 

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");
		List<String> list = new ArrayList<String>();
		String json = null;

		if (sportsName.equals("Football")) {
			list.add("Lionel Messi");
			list.add("Cristiano Ronaldo");
			list.add("David Beckham");
			list.add("Diego Maradona");
		} else if (sportsName.equals("Cricket")) {
			list.add("Sourav Ganguly");
			list.add("Sachin Tendulkar");
			list.add("Lance Klusener");
			list.add("Michael Bevan");
		} else if (sportsName.equals("Select Sports")) {
			list.add("Select Player");
		}

		json = new Gson().toJson(list);
		response.setContentType("application/json");
		response.getWriter().write(json);
	}
}

 

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
 

Other Ajax tutorial from our Blog

 
Dynamic Dependent Select Box in JSP2
 

download
 

Reference

  • jQuery.get()
  • jQuery.each()
  • Wikipedia : JSON
  •  

    Read More

    AJAX Tooltip in Java Web Application using qTip2 jQuery plugin

    Posted by on Mar 29, 2015 in Ajax, J2EE, jQuery, Servlet | 0 comments

    qTip2
     
    This article discusses AJAX Tooltip in Java Web Application using qTip2 jQuery plugin. This library is used for creating Asynchronous display of tool tip.
     

    Library required

     

    Project Structure

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

    Set up from browser perspective: jQuery qTip2

     
    Jsp form which ToolTip via ajax
     

    <!DOCTYPE html>
    <html>
    <head>
    <link rel="stylesheet" href="./css/jquery.qtip.min.css" type="text/css" media="screen"/>
    <title>AJAX Tool tip using qTip2 jQuery plugin</title>
    <style>
    .qtip-content {
    	border: 1px solid grey;
    }
    
    .student-name {
    	color: blue;
    	cursor: pointer;
    }
    
    .name-style {
    	font-weight: bold;
    	font-size: 14px
    }
    
    .style {
    	font-weight: bold;
    }
    </style>
    </head>
    <body>
    <h2>Qtip2 Demo With Ajax Call</h2>
    
    <h3>Student Details</h3>
    	<p >
    		<span class="student-name" id="1" >Mohaideen</span> <br>
    		<span class="student-name" id="2">Ameer</span> <br>
    		<span class="student-name" id="3">Badru</span> <br>
    		<span class="student-name" id="4">Prabhu</span>
    	</p>
    
    <script src="./js/jquery-1.9.0.min.js"></script>
    <script src="./js/jquery.qtip.min.js"></script>
    <script>
    $(document).ready(function(){
    	
    	$('span.student-name').each(function()
    	{
    		$(this).qtip(
    		{
    		content: {
    		text: '<img  src="./image/loading.gif" alt="Loading..." />',
    			
    		ajax: {
    			url: './Qtip2Servlet',
    			type: 'GET', 
    			data: {id  :$(this).attr('id')}, 
    			dataType: 'json',
    				
    			success: function(data, status) {
    		 	   var content = new Array();
    			   content.push("<div class='name-style'>"+data.name+"</div><br>");
    			   content.push("<div class='style'>Mark : "+data.mark+"</div>");
    			   content.push("<div class='style'>Roll : "+data.id+"</div>");
    			   content.push("<div class='style'>Address : "+data.address+"</div>");
    			   content.push("<div class='style'>Phone : "+data.phoneNo+"</div>");
    			   this.set('content.text', content.join(""));
    			}
    			}
    			},
    
    			position: {				
    				at: 'bottom center', 
    				my: 'top center',
    				viewport: $(window),
    				effect: true
    			},
    
    			show: {
    				event: 'mouseover',
    				solo: true 
    			},
    			
    			hide: 'unfocus',
    			style: {
    				classes: 'qtip-light'
    			}
    		})
    	})		
    });
    </script>
    </body>
    </html>
    

    The JQuery code written on the head section of the jsp page is responsible for the AJAX call made to the servlet.
     
    Another must read:
     
    jQuery form validation using jQuery Validation plugin
    jQuery Tutorial for Beginners
     

    From the server’s perspective: Servlet

     
    In Servlet, I’m going to use a GSON library to convert Java objects to JSON strings that will be parsed by JQuery in the JSP page and will be displayed on the web page and note that I have returned the response back to jsp based on the value of ‘id’ parameter which i pass to the servlet via jQuery’s ajax() method.
     

    Servlet implementation

     

    package servlet;
    
    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import model.Student;
    import service.StudentService;
    import com.google.gson.Gson;
    
    public class Qtip2StudentServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
    
    	protected void doGet(HttpServletRequest request,
      	    HttpServletResponse response) throws ServletException, IOException {
    
    		String id = request.getParameter("id");
    		Student student = StudentService.getStudentWithId(id);
    
    		String json = new Gson().toJson(student);
    		response.setContentType("application/json");
    		response.getWriter().write(json);
    	}
    }
    

     

    Model class

     

    package model;
    
    public class Student {
    
    	private String name;
    	private String mark;
    	private String id;
    	private String address;
    	private String phoneNo;
    
    	public String getName() {
    		return name;
    	}
    
    	public String getMark() {
    		return mark;
    	}
    
    	public String getId() {
    		return id;
    	}
    
    	public String getAddress() {
    		return address;
    	}
    
    	public String getPhoneNo() {
    		return phoneNo;
    	}
    
    	public void setName(String name) {
    		this.name = name;
    	}
    
    	public void setMark(String mark) {
    		this.mark = mark;
    	}
    
    	public void setId(String id) {
    		this.id = id;
    	}
    
    	public void setAddress(String address) {
    		this.address = address;
    	}
    
    	public void setPhoneNo(String phoneNo) {
    		this.phoneNo = phoneNo;
    	}
    }
    

     

    Business class

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

    package service;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import model.Student;
    
    public class StudentService {
    
    	public static List<Student> getStudentList() {
    
    		List<Student> listOfStudent = new ArrayList<Student>();
    
    		Student s1 = new Student();
    		s1.setName("Mohaideen");
    		s1.setMark("98");
    		s1.setAddress("Chennai India");
    		s1.setPhoneNo("+91- 123456789");
    		s1.setId("1");
    		listOfStudent.add(s1);
    
    		Student s2 = new Student();
    		s2.setName("Ameer");
    		s2.setMark("90");
    		s2.setAddress("Kolkatta India");
    		s2.setPhoneNo("+91- 542789");
    		s2.setId("2");
    		listOfStudent.add(s2);
    
    		Student s3 = new Student();
    		s3.setName("Badru");
    		s3.setMark("97");
    		s3.setAddress("Bangalore India");
    		s3.setPhoneNo("+91- 123456");
    		s3.setId("3");
    		listOfStudent.add(s3);
    
    		Student s4 = new Student();
    		s4.setName("Prabhu");
    		s4.setMark("88");
    		s4.setAddress("Vizag India");
    		s4.setPhoneNo("+91- 6789012");
    		s4.setId("4");
    		listOfStudent.add(s4);
    
    		return listOfStudent;
    
    	}
    
    	public static Student getStudentWithId(String id) {
    
    		List<Student> listOfStudent = getStudentList();
    
    		Student targetStudent = null;
    
    		for (Student student : listOfStudent) {
    
    			if (student.getId().equalsIgnoreCase(id)) {
    				targetStudent = student;
    				break;
    			} else {
    				continue;
    			}
    		}
    		return targetStudent;
    	}
    }
    

     

    web.xml

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

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

     

    Demo

     
    While loading tooltip from server side, a simple loading image gets displayed as below.
     
    qTip2-Loading
     
    Once the data is loaded from server side via ajax, that data is displayed in the browser as shown below.
     
    qTip2-qtip
     

    download

    Read More

    Ajax implementation in Servlet without jQuery plugin

    Posted by on Mar 7, 2015 in Ajax, Servlet | 0 comments

    Ajax in Servlet without jQuery

     

    AJAX is a technique for creating better, faster, and more interactive web applications. With AJAX, your JavaScript can communicate directly with the server, using the JavaScript XMLHttpRequest object. With this object, your JavaScript can transfer data with a web server, without reloading the page.
     
    This post elaborates on how to implement Ajax in Servlet application.
     
    ** UPDATE: Servlet Complete tutorial now available here.
     

    Folder Structure

     
    AjaxWithOut Jquery
     

    Jsp Page

     

    <html>
    <head>
    <title>Ajax implementation in Servlet without Using jQuery</title>
    <script type="text/javascript" src="js/ajax.js"></script>
    </head>
    
    <body>
    	<h3>Ajax implementation in Servlet without jQuery</h3>
    	<br />
    	<div id="ajaxResponse" style="color: red; font-weight: bold"></div>
    	<br /> Please Enter your Name :
    	<input type="text" id="userName" onblur="doAjaxCall();" />
    	<br />
    </body>
    </html>
    

     

    JS File

     
    File: ajax.js
    In this file we will fire ajax to call java servlet.

    //Get XMLHTTP Object
    function getXMLHTTPObject() {
    	var xmlhttpObject = null;
    	try {
    		// For Old Microsoft Browsers
    		xmlhttpObject = new ActiveXObject("Msxml2.XMLHTTP");
    	} catch (e) {
    		try {
    			// For Microsoft IE 6.0+
    			xmlhttpObject = new ActiveXObject("Microsoft.XMLHTTP");
    		} catch (e1) {
    			// No Browser accepts the XMLHTTP Object then false
    			xmlhttpObject = false;
    		}
    	}
    	if (!xmlhttpObject && typeof XMLHttpRequest != 'undefined') {
    		// For Mozilla, Opera Browsers
    		xmlhttpObject = new XMLHttpRequest();
    	}
    	// Mandatory Statement returning the ajax object created
    	return xmlhttpObject;
    }
    
    // Change the value of the outputText field
    function setAjaxOutput() {
    	document.getElementById('ajaxResponse').innerHTML = xmlhttpObject.responseText;
    }
    
    function handleServerResponse() {
    	if (xmlhttpObject.readyState == 4) {
    		if (xmlhttpObject.status == 200) {
    			setAjaxOutput();
    		} else {
    			alert("Error during AJAX call. Please try again");
    		}
    	}
    }
    
    // Implement business logic
    function doAjaxCall() {
    	xmlhttpObject = getXMLHTTPObject();
    	if (xmlhttpObject != null) {
    		var URL = "AjaxAction?userName="
    				+ document.getElementById('userName').value;
    		xmlhttpObject.open("POST", URL, true);
    		xmlhttpObject.send(null);
    		xmlhttpObject.onreadystatechange = handleServerResponse;
    	}
    }
    

     

    Recommended reading:

  • AJAX in Servlet & jsp using JQuery
  • 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 AjaxServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
    
    	protected void doPost(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:

  • 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

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

     

    Demo

     
    Ajax WithOut Jquery Demo
     
    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)”.
     
    download
     

    Read More

    Pagination in Servlet and JSP using jQuery jTable plugin

    Posted by on Sep 30, 2014 in Ajax, J2EE, jQuery, jTable, Servlet | 7 comments

     
    pagination in j2ee
     
    This is the 3rd article on jQuery jTable plugin that describes on how to implement pagination feature to do server side paging and here I have not explained about how to setup jTable plugin in java web application. So If you have not read my previous articles “Setting up JQuery jTable plugin in Java web application” and “Ajax based curd operation in Java web application using JQuery jTables plugin”, I will recommend that you read that article first because first one explains how you can integrate the JTable plugin in Java web application and in second article explains on how to implement ajax based curd operation. This article will assume that the code for the integration of jQuery JTable plugin is implemented, and only the code required for implementing pagination in Java web application using jTable will be explained here.
     

    Setup

     
    Now download the sample application of my previous tutorial and import the project in eclipse. Now follow the steps in previous tutorial to create table in database and make sure you have atleast 5 records in the table.
     
    Now on running this application, you will see a table displaying records without pagination such as the one shown below.
     
    Integrating-jQuery-jTable-plugin-with-Struts2-framework
    Now the following steps are needed to be followed to enable paging feature in jTable
     

    Changes from the browser perspective: jTable

     
    To enable paging, paging option must set to true. You can also set pageSize option (default value is 10) in jQuery Script code.

    $('#StudentTableContainer').jtable({
        //...
        paging: true, //Set paging enabled
        pageSize: 3, //Set page size
        actions: {
            //...
        },
        fields: {
            //...
        }
    });
    

     
    Note: pageSize sets the initial number of records to be displayed per page.
     
    Modified Jsp page is shown below
     

    <!DOCTYPE html>
    <html>
    <head>
    <title>Pagination in Java Web Applications using jTable plugin</title>
    <!-- Include one of jTable 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" />
    <!-- Include jTable script file. -->
    <!-- Include 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',
               paging: true, //Enable paging
               pageSize: 3, //Set page size (default: 10)           
               actions: {
                   listAction: 'Controller?action=list',
                   createAction:'Controller?action=create',
                   updateAction: 'Controller?action=update',
                   deleteAction: 'Controller?action=delete'
               },
    		fields : {
    			studentId : {
    				title : 'Student Id',
    				sort :true,
    				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');
    });
    </script>
    
    </head>
    <body>
    <div style="text-align: center;">
    	<h4>Pagination in Java Web Applications jTable</h4>
    	<div id="StudentTableContainer"></div>
    </div>
    </body>
    </html>
    

     

    Changes from the server’s perspective: Servlet

     
    If paging is enabled in jsp then jTable sends two query string parameters to the server on listAction AJAX call:
    jtStartIndex: Start index of records for current page.
    jtPageSize: Count of maximum expected records.

    And it expects additional information from server:
    TotalRecordCount: Total count of records.
     
    In our previous example the url specified in the ‘listAction‘ option has business logic to fetch all records from database. Now in order to handle pagination this ‘listAction’ option should return only the part of resultset for each page, So handle this there are two changes that has to be done in the server side .
     
    1. In order to return only a subset of records according to the page offset (jtStartIndex and jtPageSize), sql query used in CRUDDao should be modified with query below,
    In case of Oracle database:
    “SELECT * from (Select M.*, Rownum R from STUDENT M) where r > ” + < jtStartIndex> +” and r <= "+< jtStartIndex + jtPageSize >;
     
    In case of MySql database:

    select * from STUDENT limit <jtStartIndex>,<jtPageSize>
    

     
    Changes made in CRUDDao at getAllStudents function
     

    public List<Student> getAllStudents(int startPageIndex, int recordsPerPage) 
    {
    	List<Student> students = new ArrayList<Student>();
    	int range = startPageIndex+recordsPerPage;
    	String query="SELECT * from 
            (Select M.*, Rownum R From STUDENT M) where 
            r > " + startPageIndex +" and r <= "+range;
    	System.out.println(query);
    	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;
    }
    

     
    2. As mentioned above, jTable need TotalRecordCount to be present in the json response, For which add the following function in CRUDDao which returns total Record Count value present in database.
     

    public int getStudentCount()
    {
    	int count=0;
    	try 
    	{
    	   Statement stmt = dbConnection.createStatement();
    	   ResultSet rs = stmt.executeQuery("SELECT COUNT(*) AS COUNT FROM STUDENT");
    	   while (rs.next()) 
    	   {
    	 	count=rs.getInt("COUNT");
    	   }
    	} 
    	catch (SQLException e) 
    	{
    		System.err.println(e.getMessage());
    	}
    	return count;
    }
    

     

    Changes made in Controller

     
    The following changes where made in the logic inside the if loop -> ‘if(action.equals(“list”))’

    HashMap<String, Object> JSONROOT = new HashMap<String, Object>();
    
    if (action.equals("list")) {
    	try {				
    	// Fetch Data from User Table
    	int startPageIndex = Integer.parseInt(request.getParameter("jtStartIndex"));
    	int recordsPerPage = Integer.parseInt(request.getParameter("jtPageSize"));
    
    	// Fetch Data from Student Table
    	studentList = dao.getAllStudents(startPageIndex, recordsPerPage);
    	// Get Total Record Count for Pagination
    	int userCount = dao.getStudentCount();
    
    	// Return in the format required by jTable plugin
    	JSONROOT.put("Result", "OK");
    	JSONROOT.put("Records", studentList);
    	JSONROOT.put("TotalRecordCount", userCount);
    
    	// 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);
    	}
    }
    

     
    Now on running the application, with the above changes, the final demo looks as shown below:
     
    Pagination-Cover
     
    download
     

    Reference

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

    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 | 38 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

     

    <!DOCTYPE html>
    <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”
     
    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(JSONROOT);
    

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

    Reading

     
    Method to jTable to get a list of records:
     

    HashMap<String, Object> JSONROOT = new HashMap<String, Object>();
    
    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

     

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

    Reference

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

    Read More
    Page 1 of 41234