Pages Navigation Menu

Coding is much easier than you think

Struts2 AngularJS integration

Posted by on May 2, 2015 in Ajax, AngularJS, Struts-2 | 5 comments

Angular2
 
In this post, we will learn to implement AJAX calls from a JSP page to a Struts 2 Action class using AngularJS and update the same JSP page back with the Json response from the Struts 2.
 

Library Required

 
Since Angular can send and receive only in json format, 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.
 

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 Struts2 and for updating the response back in the JSP.
 

Jsp Page

 
File: index.jsp

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>AJAX with Struts 2 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.get("angularAction").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 data-ng-app="myApp">
	<div data-ng-controller="MyController">
		<button data-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;
        
        // Create Getters and Setters 
}

 
Recommended Reading:

 

Action Class

 
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 AngularJs and all the variables that have a getter method can be retrieved in the AngularJs code.

package com.action;

import com.model.PersonData;
import com.opensymphony.xwork2.Action;

public class AngularAction implements Action {

	private PersonData personData = new PersonData();

	public String execute() {

		personData.setFirstName("Mohaideen");
		personData.setLastName("Jamil");
		return SUCCESS;
	}

	public PersonData getPersonData() {
		return personData;
	}

	public void setPersonData(PersonData personData) {
		this.personData = personData;
	}
}

 

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.
 

struts.xml

 
Since the response needed by AngularJs is of type json, so we need to convert the PersonData objects to json strings, for this you need to configure 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="angularAction" class="com.action.AngularAction">
	<result type="json">
          <param name="root">personData</param>
	  <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

     
    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

    Pagination in Struts 2 using jQuery jTable plugin

    Posted by on Oct 6, 2014 in Ajax, jQuery, Struts-2 | 1 comment

     
    jtable_pagination in struts2
     
    This is the third article on jQuery jTable plugin in Struts 2 that describes on how to implement pagination feature to do server side paging in struts 2 using the JQuery jTable plugin and here I have not explained about how to setup jTable plugin in struts 2. So If you have not read my previous articles “Setting up JQuery jTable plugin in Struts 2″ and “Ajax based curd operation in Struts 2 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 Struts 2 application and second article explains on how to implement ajax based curd operation. This article will assume that the code for the integration of the jQuery JTable plugin is implemented, and only the code required for implementing pagination in Struts 2 using jTable is explained here.
     

    Setup

     
    As described above, the prerequisite for this code is that you integrate the jQuery jTable plugin into the Struts 2. You can find detailed instructions here, at JQuery jTable plugin in Struts 2, so now I am going to take the sample application I created for explaining AJAX based crud operations in jTable plugin and continue to implement paging for that application.
     
    1. Download sample application from here and import the project in eclipse
    2. Follow the steps in this article here to create table in database.
     

    Steps to enable Paging:

     

    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

     

    <!DOCTYPE html>
    <html>
    <head>
    <title>jTable Pagination in Java Web Applications</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. -->
    <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 : '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');
    });
    </script>
    
    </head>
    <body>
    <div style="text-align: center;">
    	<h3>jTable Pagination in Java Web Applications</h3>
    	<div id="StudentTableContainer"></div>
    </div>
    </body>
    </html>
    

     

    From the server’s perspective: Servlet

     
    If paging is enabled, 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 fetch only a part of records for each page, So handle this there are two changes that has to be done in the server side .
     
    1. Modify oracle query to fetch only a subset of records based on the jtStartIndex and jtPageSize.

    Since these values are sent along with the request as string parameters by jTable so add following member variable in struts 2 action class and create getters and setters for the same

    // Holds Start Page Index
    private int jtStartIndex;
    // Hold records to be displayed per Page 
    private int jtPageSize;	
    

     
    2. As mentioned above, jTable need TotalRecordCount to be present in the json response, For which add a member variable totalRecordCount in struts 2 action class and create getters and setters for the same.
     
    Now replace the list method in action class with the below code,
     

    public String list() {
    try {
    	// Fetch Data from Student Table
    	records = dao.getAllStudents(jtStartIndex, jtPageSize);
    	// Get Total Record Count for Pagination
    	totalRecordCount = dao.getStudentCount();
    	result = "OK";
    } catch (Exception e) {
    	result = "ERROR";
    	message = e.getMessage();
    }
    return Action.SUCCESS;
    }
    

     

    Changes made at Dao class

     
    Add below two methods in ‘CrudDao.java’ file

    1. Method to get the count of total number of records in the result set.
     

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

     
    2. In order to return only a subset of records according to the page offset (jtStartIndex and jtPageSize), oracle query should be modified as follows,

    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>
    

     

    Now modify getAllUsers in CurdDao.java using below code
     

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

     
    This function returns only a subset of records according to the page offset (jtStartIndex and jtPageSize).
     
    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
     

    Read More

    AJAX implementation in Struts 2 using JQuery and JSON

    Posted by on Oct 5, 2014 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

    Autocomplete in Struts 2 using Jquery

    Posted by on Sep 27, 2014 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 on Sep 20, 2014 in Ajax, jQuery, Struts-2 | 69 comments

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

    Steps done to set up our application for jTable

     
    Libraries required for the setup,

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

    JSP

     

    <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

    FieldError in Struts 2 Example

    Posted by on Aug 14, 2014 in Struts 2 Tutorial, Struts-2 | 6 comments

     
    Field error in Struts 2
     
    In our previous tutorial we learnt about actionError and actionMessage in struts 2, in this tutorial, we are going to describe the fielderror tags. The fielderror tag is a UI tag that renders field errors if they exist.
     

    download

     
    ** UPDATE: Struts 2 Complete tutorial now available here.
     

    Folder Structure

     
    Struts 2 Field Error
     

    Action Class

     
    Develop an action class using addFieldError(String fieldName, String errorMessage)method. This method adds an error message for a given field to the corresponding jsp page.

    Here the error messages is added to each field individually using the addFieldError() method. The error messages can either be specified in a separate property file or can be added directly in the Action class itself.
     

    package com.action;
    
    import com.opensymphony.xwork2.ActionSupport;
    
    public class LoginAction extends ActionSupport {
    
    	private static final long serialVersionUID = 6677091252031583948L;
    
    	private String userName;
    	private String password;
    
    	public String getPassword() {
    		return password;
    	}
    
    	public void setPassword(String password) {
    		this.password = password;
    	}
    
    	public String execute() {
    		return SUCCESS;
    	}
    
    	public String getUserName() {
    		return userName;
    	}
    
    	public void setUserName(String userName) {
    		this.userName = userName;
    	}
    
    	public void validate() {
    
    		if (userName.isEmpty()) {
    			addFieldError("userName", "Username can't be blank");
    		}
    		if (password.isEmpty()) {
    			addFieldError("password", "Password Can't be blank");
    		}
    		else {
    		addActionMessage("Welcome " + userName + ", You have been Successfully Logged in");
    		}
    	}
    }
    

     
    Here when either of userName or password is empty then fieldError is added this action via addFiedError method, so the execute method does not get invoked, and interceptors take case altering the flow of response by sending “error” string.
     
    If userName and password are valid then a success message is added to actionMessage, the execute method get invoked, the jsp page get displayed based on execute methods returned value.
     
    Recommended Article

     

    JSP

     
    File: Login.jsp
     
    Create a jsp page that will display your field error messages (when fails to logged-in) using <s:fielderror/> tag as shown:
     

    <%@taglib uri="/struts-tags" prefix="s"%>
    <html>
    <head>
    <title>Login</title>
    </head>
    <body>
    <h3>FieldError in Struts 2</h3>
    <s:form action="loginUser">
    	<s:textfield name="userName" placeholder="Username" label="Username" />
    	<s:password name="password" placeholder="Password" label="Password" />
    	<s:submit value="Submit" />
    </s:form>
    </body>
    </html>
    

     
    File : Success.jsp
     

    <%@ taglib prefix="s" uri="/struts-tags"%>
    <html>
    <head>
    <title>Welcome Page</title>
    </head>
    <body>
    <h3>ActionError &amp; ActionMessage Example</h3>
    	<s:actionmessage />
    </body>
    </html>
    

     

    Note :

    We have done the coding such that If the username or password is empty , then the user will be forwarded to login.jsp where the field error added using addFieldError will get displayed.


     
    You might be interested to read:

     

    struts.xml

     
    Make sure that the struts.xml has the following mapping

    <struts>
     <package name="default" extends="struts-default">
         <action name="loginUser" class="com.action.LoginAction">
    	<result name="success">success.jsp</result>
    	<result name="input">login.jsp</result>
         </action>
     </package>
    </struts>
    

     
    The web.xml configuration is same as given in hello world programe.
     

    Demo

     
    On running the application
     
    FieldError in Struts 2
     
    When Username or password is empty, display error message set by <s:fielderror/>
     
    FieldError in Struts 2 Error
     
    When Username and password is non empty, then application executes successfully and redirects to success.jsp and displays the ActionMessage setted in Validate method via <s:actionmessage/> tag.
     
    FieldError in Struts 2 Action Message
     

    Reference

     
    FieldError Apache
     

    Read More
    Page 1 of 1012345...10...Last »