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

    AngularJS Interacting with Java Servlet using JSON

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

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

    How to use?

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

    Jsp Page

     

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="ISO-8859-1">
    <title>AJAX with Servlets using AngularJS</title>
    <script type="text/javascript" src="js/angular.min.js"></script>
    <script>
    var app = angular.module('myApp', []);
    
    function MyController($scope, $http) {
    
    	$scope.getDataFromServer = function() {
    		$http({
    			method : 'GET',
    			url : 'javaAngularJS'
    		}).success(function(data, status, headers, config) {
    			$scope.person = data;
    		}).error(function(data, status, headers, config) {
    			// called asynchronously if an error occurs
    			// or server returns response with an error status.
    		});
    
    	};
    };
    </script>
    </head>
    <body>
    <div ng-app="myApp">
    	<div ng-controller="MyController">
      	   <button ng-click="getDataFromServer()">Fetch data from server</button>
    	   <p>First Name : {{person.firstName}}</p>
    	   <p>Last Name : {{person.lastName}}</p>
    	</div>
    </div>
    </body>
    </html>
    

     

    HTML – Data Binding

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

    ng-click
    Angular on click event
     

    Model class

     

    package com.model;
    
    public class PersonData {
    
    	private String firstName;
    	private String lastName;
    
    	public String getFirstName() {
    		return firstName;
    	}
    
    	public void setFirstName(String firstName) {
    		this.firstName = firstName;
    	}
    
    	public String getLastName() {
    		return lastName;
    	}
    
    	public void setLastName(String lastName) {
    		this.lastName = lastName;
    	}
    
    }
    

     
    Recommended Reading:

     

    Servlet

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

    package com.controller;
    
    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.google.gson.Gson;
    import com.model.PersonData;
    
    public class AngularJsServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
    
    	public AngularJsServlet() {
    		super();
    	}
    
    	protected void doGet(HttpServletRequest request,
    	    HttpServletResponse response) throws ServletException, IOException {
    		PersonData personData = new PersonData();
    		personData.setFirstName("Mohaideen");
    		personData.setLastName("Jamil");
    
    		String json = new Gson().toJson(personData);
    		response.setContentType("application/json");
    		response.getWriter().write(json);
    	}
    }
    

     

    Code Explanation

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

    Web.xml

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

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

     

    Demo

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

    AngularJS demo

    download
     

    Reference

     
    AngularJS API Docs

    Read More