Pages Navigation Menu

Coding is much easier than you think

AJAX implementation in Struts 2 using JQuery and JSON

Posted by in Ajax, jQuery, Struts-2 | 54 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 :

 

<%@ 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 :

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">
	<param name="excludeNullProperties">true</param>
	<param name="noCache">true</param>
   </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>

 
Recommended Article :

  • How to Call Struts2 action from java script
  •  

    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
     
    download

    Read More

    Pagination in Servlet and JSP using jQuery jTable plugin

    Posted by 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

    jQuery form validation using jQuery Validation plugin

    Posted by in Ajax, jQuery | 2 comments

     
    Jquery
     
    This article discusses client-side validation using jQuery’s validation plugin. This jQuery plugin has a bunch of standard validation methods such as a required field, valid email or URL, minimum and maximum lengths for a field, etc. In addition to that you can customize the look and feel of the error messages and their placement.
     

    Library required

    Let us start with a simple example.
     

    Jsp

     

    <!DOCTYPE HTML>
    <html>
    <head>
    <script src="js/jquery.min.js"></script>
    <script src="js/jquery.validate.min.js"></script>
    <script src="js/userValidation.js"></script>
    <link href="css/myCSS.css" rel="stylesheet">
    <title>jQuery form Validation tutorial</title>
    </head>
    <body>
    <form id="form" name="" action="">
      <div class="fieldgroup">
    	     <label for="name">Name:</label>
                 <input name="name" size="20" />
    	     <p>
    		<input class="submit" type="submit" value="Submit" />
    	     </p>
      </div>
    </form>
    </body>
    

     

    Points to be noted

    • Remember to include the the jQuery library and the validation plugin in the head section of JSP.
    • Remember to assign the id attribute of the form and the name attribute of all the fields that you want to validate.

    Fire the jQuery Validation Plugin (userValidation.js File)

     

    $(function() {
       $("#form").validate({
    	rules : {
    		name : {
    			required : true,
    			minlength : 4,
    			maxlength : 20,
    		}
    	},
    	messages : {
    		name : {
    			required : "Please enter a name",
    			minlength : $.format("Minimum {0} characters required!"),
    			maxlength : $.format("Maximum {0} characters allowed!")
    		}
    	}
      });
    });
    

     
    All we are doing here is initializing the validation of the form using the validate() function. It can take several parameters. In the example above, we use only two of them, but you can find a list of all the options for the validate() function at Validate options.
     
    The two parameters we used in validate method are:
     
    rules: allows you to specify which fields you want to validate.
    messages: allows you to specify the error message for a particular field. If you don’t specify it, a default message is provided that says “this field is required”.
     
    In the example above, we only used three validation methods (required, minlength and maxlength). I’ve also introduced the format method in the message. This lets us replace the argument given for minlength and maxlength, such that we don’t need to hard-code that value if they ever change.
     
    There are several other methods that can be used here. You can find list of built-in validation methods at Validation Methods.
     

    Custom Validation Rules:

     
    Suppose if you cant find any suitable built-in method for certain situation, then you can write your own validation methods. For example, there is no built-in method to validate Alpha character, we need to define our own method.
     

    $(function() {
    	$("#form").validate({
    		rules : {
    			name : {
    				customvalidation : true
    			}
    		}
    	});
    	$.validator.addMethod("customvalidation", function(value, element) {
    		return /^[A-Za-z_ -]+$/.test(value);
    	}, "Alpha Characters Only.");
    });
    

     
    Here I have defined our own validation method by calling the jQuery.validator.addMethod()method. This method takes three parameters:

    • name: The name of the method, used to identify and referencing it, must be a valid javascript identifier.
    • method: the actual method implementation, returning true if an element is valid.
    • message: The default message to display for this method.

     
    You may also like …

     

    jQuery Validation CSS

     
    Note: the jQuery Validation Plugin adds class error to the inputs/labels. You only style them!
     

    #form label.error {
    	color: red;
    }
    #form input.error {
    	border: 1px solid red;
    }
    

     

    Caution:

     
    This validation happens only on the client side. So if there is a JavaScript error, the browser could ignore the remaining validation and submit the form to the server. So it would be better to validate the data again on the server side.
     

    Demo

     
    jquery Validation demo
     
    download

    Read More

    Autocomplete in Struts 2 using Jquery

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

     
    I have already written a detailed post on Autocompleter Textbox & dropdown in Struts 2 using struts2-dojo-plugin.jar. In this post, I am going to describe how to implement Ajax based autocomplete in Struts 2 web application using jQuery plugin. jQuery Autcomplete is part of the jQuery UI library which allows converting a normal textbox into an autocompleter textbox by providing a data source for the autocompleter values.
     
    struts 2 autocompleter_2
     
    Here when user types a character in text box, jQuery will fire an ajax request using autocomplete plugin to Struts 2 action class, which in turn call the dao class which connects to the database and returns the required data back as an array list, this list should be returned in json format to the success function of ajax call. So to handle this 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. This guide will teach you on how to implementation AJAX in Struts 2 using JQuery and JSON
     

    Library

     
    struts2-json-plugin-2.x.x.jar
    ojdbc14.jar
    jquery-1.10.2.js
    jquery-ui.js
    jquery-ui.css
     
    Now create a dynamic web project in eclipse and add the above jars in classpath of the project and the project structure should look like shown below.
     

    Project Structure


     
    struts 2 autocompleter
     

    Jsp page

    We are done with the setup. Now create a new jsp file under WebContent folder to display the data fetched from database into autocomplete textbox. Now to implement this page with Autocompleter feature and make sure that you referred the jQuery core and jQueryUI libraries.
     

    <%@ taglib prefix="s" uri="/struts-tags"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="ISO-8859-1">
    <title>Autocomplete in Struts 2 using Jquery and JSON</title>
    <script src="js/jquery-1.10.2.js"></script>
    <script src="js/jquery-ui.js"></script>
    <script src="autocompleter.js"></script>
    <link rel="stylesheet" href="css/jquery-ui.css">
    <link rel="stylesheet" href="style.css">
    
    </head>
    <body>
    	<div class="header">
    		<h3>Autocomplete in Struts 2 using Jquery and JSON</h3>
    	</div>
    	<br />
    	<br />
    	<div class="search-container">
    		<div class="ui-widget">
    			<s:textfield id="search" name="search" />
    		</div>
    	</div>
    </body>
    </html>
    

     

    Js file

     
    Here we get data from database via ajax and apply autocompleter
     

    $(document).ready(function() {
    	$(function() {
    		$("#search").autocomplete({
    		source : function(request, response) {
    			$.ajax({
    				url : "searchAction",
    				type : "POST",
    				data : {
    					term : request.term
    				},
    				dataType : "json",
    				success : function(jsonResponse) {
    					response(jsonResponse.list);
    				}
    			});
    			}
    		});
    	});
    });
    

    When a user types a character in text box ,jQuery will fire an ajax request to the controller, in this case controller is SearchController as mentioned in the above js file.
     
    Recommended reading :

  • AJAX implementation in Struts 2 using JQuery and JSON
  •  

    Business class

     
    Next step is to create a class that would fetch data from database.

    package com.dao;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.util.ArrayList;
    
    public class DataDao {
    	private Connection connection;
    
    	public DataDao() throws Exception {
    		connection = DBUtility.getConnection();
    	}
    
    	public ArrayList<String> getFrameWork(String frameWork) {
    		ArrayList<String> list = new ArrayList<String>();
    		PreparedStatement ps = null;
    		String data;
    		try {
    			ps = connection
    					.prepareStatement("SELECT * FROM JAVA_FRAMEWORK  WHERE FRAMEWORK  LIKE ?");
    			ps.setString(1, frameWork + "%");
    			ResultSet rs = ps.executeQuery();
    			while (rs.next()) {
    				data = rs.getString("FRAMEWORK");
    				list.add(data);
    			}
    		} catch (Exception e) {
    			System.out.println(e.getMessage());
    		}
    		return list;
    	}
    }
    

     

    Data Access object

     
    Connecting To Database Using JDBC

    package com.dao;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    
    public class DBUtility {
    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;
    	}
    	}
    }
    

     

    Action class

     
    Now Create the action class to handle Ajax call; in action class you need to create instance variables and its respective getter and setter methods since all the variables which have a setter can be set to the values as which are passed as parameters by jQuery and all the variables that have a getter method can be retrieved in the client javascript code.

    package com.action;
    
    import java.util.ArrayList;
    
    import com.dao.DataDao;
    import com.opensymphony.xwork2.Action;
    
    public class AutoCompleteAction implements Action {
    	// Received via Ajax request
    	private String term;
    	// Returned as responce
    	private ArrayList<String> list;
    
    	public String execute() {
    		try {
    			System.out.println("Parameter from ajax request : - " + term);
    			DataDao dataDao = new DataDao();
    			list = dataDao.getFrameWork(term);
    		} catch (Exception e) {
    			System.err.println(e.getMessage());
    		}
    		return SUCCESS;
    	}
    
    	public ArrayList<String> getList() {
    		return list;
    	}
    
    	public void setList(ArrayList<String> list) {
    		this.list = list;
    	}
    
    	public String getTerm() {
    		return term;
    	}
    
    	public void setTerm(String term) {
    		this.term = term;
    	}
    }
    

     
    As mentioned in the code, the action class will call the business service class which in turn creates the necessary connection and returns the data back as an array list.
     
    Also read :

  • Gridview in Struts2 using jQuery DataTable
  • CRUD Operations in Struts 2 using jTable jQuery plugin via Ajax
  •  

    struts.xml

     
    In struts.xml, create a package that extend json-default and specify the result type of your action class inside this package to be json. This package component is present in struts2-json-plugin-2.x.x.jar

    Please read the article on AJAX implementation in Struts 2 using JQuery and JSON to understand about “json-default” package better.
     

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
    <struts>
      	<package name="default" extends="json-default">
    		<action name="searchAction" class="com.action.AutoCompleteAction">
    			<result type="json">
                     	   <param name="excludeNullProperties">true</param>
                	           <param name="encoding">UTF-8</param>
     	                  <param name="noCache">true</param>
                           </result>
    		</action>
    	</package>
    	
    </struts>
    

     

    web.xml

     
    Make sure you have done mapping in web.xml file as given below,

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

     

    Demo

     
    struts 2 autocompleter_2
     
    download
     
    If you have any other suggestion on above topic, do let me know via comments.

    Read More

    CRUD Operations in Struts 2 using jTable jQuery plugin via Ajax

    Posted by 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

     

    <html>
    <head>
    <title>jTable in Struts 2</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/userDefinedJtable.js" type="text/javascript"></script>
    
    </head>
    <body>
    <div style="text-align: center;">
    	<h3>AJAX based CRUD operation in Struts 2 using jTable plugin</h3>
    	<div id="StudentTableContainer"></div>
    </div>
    </body>
    </html>
    

     

    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<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
     
    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<Student> 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<Student> getRecords() {
    		return records;
    	}
    
    	public String getResult() {
    		return result;
    	}
    
    	public String getMessage() {
    		return message;
    	}
    
    	public void setRecords(List<Student> 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

    <struts>
    	<package name="default" extends="json-default">
    		<action name="*Action" class="com.action.JtableAction"
    			method="{1}">
    			<result type="json">/index.jsp</result>
    		</action>
    		<action name="getJSONResult" class="com.action.JtableAction" method="list">
    			<result type="json" />
    		</action>
    	</package>
    </struts>
    

     

    web.xml

     

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

     

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

     

    <!DOCTYPE html>
    <html>
    <head>
    <title>jqGird in Servlet</title>
    
    <link rel="stylesheet" href="jqueryJs/jquery-ui.css">
    <link rel="stylesheet" href="gridJs/css/ui.jqgrid.css">
    
    <script src="jqueryJs/external/jquery/jquery.js"></script>
    <script src="gridJs/js/i18n/grid.locale-en.js"></script>
    <script src="gridJs/js/jquery.jqGrid.src.js"></script>
    <script src="jqueryJs/jquery-ui.js"></script>
    
    <script src="js/getJqGridData.js"></script>
    
    </head>
    <body>
    	<table id="list">
    		<tr>
    			<td />
    		</tr>
    	</table>
    	<div id="pager"></div>
    </body>
    </html>
    

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

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

     

    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
    Page 2 of 41234