Struts2 AngularJS integration
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
AJAX with Struts 2 using AngularJS First Name : {{person.firstName}}
Last Name : {{person.lastName}}
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:
- AJAX implementation in Struts 2 using JQuery and JSON
- jQuery Tutorial for Beginners
- GridView in Struts2 using jQuery DataTable via Ajax
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.
personData true true
Note: json-default package extends struts-default
Web.xml
Struts2 struts2 org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter struts2 /* index.jsp
Recommended Article :
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).
Click button: Fetch data from server to pass HTTP request using angularJS where Java servlet will return data as below:
AngularJS demo
Reference
Read MoreAngularJS Interacting with Java Servlet using JSON
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
AJAX with Servlets using AngularJS First Name : {{person.firstName}}
Last Name : {{person.lastName}}
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:
- AJAX in Servlet & jsp using JQuery
- jQuery Tutorial for Beginners
- Autocomplete in java web application using Jquery and JSON
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
index.jsp javaAngularJS com.controller.AngularJsServlet javaAngularJS /javaAngularJS
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).
Click button: Fetch data from server to pass HTTP request using angularJS where Java servlet will return data as below:
AngularJS demo
Reference
Read MoreAjax Cascading DropDownList in JSP & Servlet using JQuery and JSON
There are times in a web application where you want to populate a dropdown list based on the value of another drop down list. In this example, we will be creating a dropdown list for favorite spots and favorite player; since this scenario involves in returning complex java objects like lists, maps, etc, so I’m using JSON for this purpose.
In the article on AJAX in Servlet & jsp using JQuery I have demonstrated on returning simple object from servlet to jsp via jquery.
Library required
Project Structure
Steps done to set up our Servlet for JSON
From the browser perspective: jQuery
jQuery allows you to fire an ajax request via get or post method and expects a JSON object as a response, as described in my previous post the first and second parameter of these method are the url and a key-value pair and the third argument of get method is a function that defines what is to be done with the response that is got back from the Servlet.
Recommended reading:
Jsp Page
AJAX in Servlet using JQuery and JSON AJAX in Servlet using JQuery and JSON
Select Favorite Sports:
Select Favorite Player:
Here jquery will fire an ajax request when the value of the first dropdown is changed(id=”sports”).
Another must read:
- AJAX Tooltip in Java Web Application using qTip2 jQuery plugin
- jQuery form validation using jQuery Validation plugin
- Pagination in Servlet and JSP using jQuery jTable plugin
From the server’s perspective: Servlet
In Servlet, I’m going to use a GSON library to convert Java objects (lists, maps etc) to JSON strings that will be parsed by JQuery in the JSP page and will be displayed on the web page and note that I have returned the response back to jsp based on the value of sports parameter which i pass to the servlet via jQuery’s get() method.
Servlet
package com.action; import java.io.IOException; import java.util.*; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; public class JsonServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String sportsName = request.getParameter("sportsName"); Listlist = new ArrayList (); String json = null; if (sportsName.equals("Football")) { list.add("Lionel Messi"); list.add("Cristiano Ronaldo"); list.add("David Beckham"); list.add("Diego Maradona"); } else if (sportsName.equals("Cricket")) { list.add("Sourav Ganguly"); list.add("Sachin Tendulkar"); list.add("Lance Klusener"); list.add("Michael Bevan"); } else if (sportsName.equals("Select Sports")) { list.add("Select Player"); } json = new Gson().toJson(list); response.setContentType("application/json"); response.getWriter().write(json); } }
Web.xml
Servlet mapping should be done in web.xml as shown below
index.jsp JsonServlet com.action.JsonServlet JsonServlet /JsonServlet/*
Demo
On selecting ‘Football’ in the first dropdown list
On selecting ‘Cricket’ in the first dropdown list
Other Ajax tutorial from our Blog
- AJAX implementation in Servlets using JQuery and JSON
- AngularJS Interacting with Java Servlet using JSON
- Refresh DIV Content Without Reloading Page using jQuery
Reference
Read More
AJAX Tooltip in Java Web Application using qTip2 jQuery plugin
This article discusses AJAX Tooltip in Java Web Application using qTip2 jQuery plugin. This library is used for creating Asynchronous display of tool tip.
Library required
Project Structure
Now Create a dynamic web project in Eclipse with following folder structure
Set up from browser perspective: jQuery qTip2
Jsp form which ToolTip via ajax
AJAX Tool tip using qTip2 jQuery plugin Qtip2 Demo With Ajax Call
Student Details
Mohaideen
Ameer
Badru
Prabhu
The JQuery code written on the head section of the jsp page is responsible for the AJAX call made to the servlet.
Another must read:
jQuery form validation using jQuery Validation plugin
jQuery Tutorial for Beginners
From the server’s perspective: Servlet
In Servlet, I’m going to use a GSON library to convert Java objects to JSON strings that will be parsed by JQuery in the JSP page and will be displayed on the web page and note that I have returned the response back to jsp based on the value of ‘id’ parameter which i pass to the servlet via jQuery’s ajax() method.
Servlet implementation
package servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import model.Student; import service.StudentService; import com.google.gson.Gson; public class Qtip2StudentServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getParameter("id"); Student student = StudentService.getStudentWithId(id); String json = new Gson().toJson(student); response.setContentType("application/json"); response.getWriter().write(json); } }
Model class
package model; public class Student { private String name; private String mark; private String id; private String address; private String phoneNo; public String getName() { return name; } public String getMark() { return mark; } public String getId() { return id; } public String getAddress() { return address; } public String getPhoneNo() { return phoneNo; } public void setName(String name) { this.name = name; } public void setMark(String mark) { this.mark = mark; } public void setId(String id) { this.id = id; } public void setAddress(String address) { this.address = address; } public void setPhoneNo(String phoneNo) { this.phoneNo = phoneNo; } }
Business class
This Business Service class which provides static data using model class.
package service; import java.util.ArrayList; import java.util.List; import model.Student; public class StudentService { public static ListgetStudentList() { List listOfStudent = new ArrayList (); Student s1 = new Student(); s1.setName("Mohaideen"); s1.setMark("98"); s1.setAddress("Chennai India"); s1.setPhoneNo("+91- 123456789"); s1.setId("1"); listOfStudent.add(s1); Student s2 = new Student(); s2.setName("Ameer"); s2.setMark("90"); s2.setAddress("Kolkatta India"); s2.setPhoneNo("+91- 542789"); s2.setId("2"); listOfStudent.add(s2); Student s3 = new Student(); s3.setName("Badru"); s3.setMark("97"); s3.setAddress("Bangalore India"); s3.setPhoneNo("+91- 123456"); s3.setId("3"); listOfStudent.add(s3); Student s4 = new Student(); s4.setName("Prabhu"); s4.setMark("88"); s4.setAddress("Vizag India"); s4.setPhoneNo("+91- 6789012"); s4.setId("4"); listOfStudent.add(s4); return listOfStudent; } public static Student getStudentWithId(String id) { List listOfStudent = getStudentList(); Student targetStudent = null; for (Student student : listOfStudent) { if (student.getId().equalsIgnoreCase(id)) { targetStudent = student; break; } else { continue; } } return targetStudent; } }
web.xml
Make sure you have done servlet mapping properly in web.xml file. An example of this is given below,
Qtip2Servlet servlet.Qtip2StudentServlet Qtip2Servlet /Qtip2Servlet index.jsp
Demo
While loading tooltip from server side, a simple loading image gets displayed as below.
Once the data is loaded from server side via ajax, that data is displayed in the browser as shown below.
Ajax implementation in Servlet without jQuery plugin
AJAX is a technique for creating better, faster, and more interactive web applications. With AJAX, your JavaScript can communicate directly with the server, using the JavaScript XMLHttpRequest object. With this object, your JavaScript can transfer data with a web server, without reloading the page.
This post elaborates on how to implement Ajax in Servlet application.
** UPDATE: Servlet Complete tutorial now available here.
Folder Structure
Jsp Page
Ajax implementation in Servlet without Using jQuery Ajax implementation in Servlet without jQuery
Please Enter your Name :
JS File
File: ajax.js
In this file we will fire ajax to call java servlet.
//Get XMLHTTP Object function getXMLHTTPObject() { var xmlhttpObject = null; try { // For Old Microsoft Browsers xmlhttpObject = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { // For Microsoft IE 6.0+ xmlhttpObject = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e1) { // No Browser accepts the XMLHTTP Object then false xmlhttpObject = false; } } if (!xmlhttpObject && typeof XMLHttpRequest != 'undefined') { // For Mozilla, Opera Browsers xmlhttpObject = new XMLHttpRequest(); } // Mandatory Statement returning the ajax object created return xmlhttpObject; } // Change the value of the outputText field function setAjaxOutput() { document.getElementById('ajaxResponse').innerHTML = xmlhttpObject.responseText; } function handleServerResponse() { if (xmlhttpObject.readyState == 4) { if (xmlhttpObject.status == 200) { setAjaxOutput(); } else { alert("Error during AJAX call. Please try again"); } } } // Implement business logic function doAjaxCall() { xmlhttpObject = getXMLHTTPObject(); if (xmlhttpObject != null) { var URL = "AjaxAction?userName=" + document.getElementById('userName').value; xmlhttpObject.open("POST", URL, true); xmlhttpObject.send(null); xmlhttpObject.onreadystatechange = handleServerResponse; } }
Recommended reading:
Servlet
Now let’s go on and write the servlet which handles this Ajax call
package com.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class AjaxServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userName = request.getParameter("userName"); if (userName.equals("")) { userName = "User name cannot be empty"; } else { userName ="Hello" + userName; } response.setContentType("text/plain"); response.getWriter().write(userName); } }
I hope the code above is self explanatory.
Also read:
Web.xml
Make sure you have done servlet mapping in web.xml as shown below
JqueryAjaxServlet index.jsp AjaxAction com.servlet.AjaxServlet AjaxAction /AjaxAction/*
Demo
On running the application the above webpage is generated, in which enter a value in the textbox and click anywhere outside the textbox, then you will see a welcome message saying “Hello (userName)”.
jQuery Tutorial for Beginners
In this article we are going to take a look at introduction to jQuery, what it is, what is does and why we should use in our website.
If you are looking to perform Ajax operations in your website with lot of cool effects on it and you are not completely familiar with java script, then jQuery is a very easy and flexible way to integrate thing like effects, Ajax, animation and so on.
A Little Bit About jQuery
jQuery is Open-Source JavaScript library that contains variety of functions and other functionality that allows you to do the effects in an easier way and it is widely used for the below advantages.
- DOM manipulation
- AJAX
- Animations
- Extensibility through plugins
Why should you use it?
- Easy to learn! It uses CSS syntax for selection
- Its tiny 93.5 KB, it loads really fast in most browsers.
- Documented jquery.com & Supported forum.jquery.com
- Cross browser compatibility: IE 6+, FF 2+ and with most major browsers
- It is the most used JavaScript library on the web today
- 39% of all sites that use JavaScript use jQuery.
How to use jQuery
In order to use jQuery you need to load it, you can either include it locally on your own server:
- <script src=”/js/jquery.js”>
Or use one of the CDN’s made available:
Introduction to DOM?
The DOM is everything you write in your html documents, images, css, all your tags, everything. When a web page is loaded, the browser creates a Document Object Model of the page. The HTML DOM model is constructed as a tree of Objects.
Example:
The DOM is a mess. There are a million different ways to accomplish things within it and many different doctypes and uppercase and lowercase are allowed attributes that sometimes need quotes, and other times don’t. JQuery is coded around all those inconsistencies.
JQuery can modify the DOM, but it can’t do so until the DOM is ready. So how can I be sure my code runs at DOM ready?
Wrap all your jQuery code with the document ready function.
$(document).ready(function(){ // all jQuery code goes here });
Load Scripts at the Bottom
Problem:
When scripts are downloading they block everything else in almost all browsers!
Solution:
Best practice: The DOM is loaded top to bottom, so include your scripts at the bottom of your page so they don’t interrupt page content downloads.
And BOOM! Goes The Dynamite!!!
Break It Down!
Basic jQuery Selectors
$("div"); // selects all HTML div elements $("#myElement"); // selects one HTML element with ID "myElement" $(".myClass"); // selects HTML elements with class "myClass" $("p#myElement"); // selects paragraph elements with ID "myElement" $("ul li a.navigation"); // selects anchors with class "navigation" that are nested in list items $("p > a"); // selects anchors that are direct children of paragraphs $("input[type=text]"); // selects inputs that have specified type $("a:first"); // selects the first anchor on the page $("p:odd"); // selects all odd numbered paragraphs $("li:first-child"); // every list item that's first child in a list
Manipulating and Accessing CSS Class Names
JQuery allows you to easily add, remove, and toggle CSS classes, which comes in handy for a variety of practical uses. Here are the different syntaxes for accomplishing this:
$("div").addClass("content"); // adds class "content" to allelements $("div").removeClass("content"); // removes class "content" from allelements $("div").toggleClass("content"); // toggles the class "content" on allelements //(adds it if it doesn't exist, and removes it if it does)
You can also check to see if a selected element has a particular CSS class, and then run some code if it does. You would check this using an if statement. Here is an example:
if ($("#myElement").hasClass("content")) { // do something here }
You could also check a set of elements (instead of just one), and the result would return “true” if any one of the elements contained the class.
Manipulating CSS Styles with jQuery
CSS styles can be added to elements easily using jQuery, and it’s done in a cross-browser fashion. Here are some examples to demonstrate this:
$("p").css("width", "400px"); // adds a width to all paragraphs $("#myElement").css("color", "blue") // makes text color blue on element #myElement $("ul").css("border", "solid 1px #ccc") // adds a border to all lists
Hide and Seek
$("div").show();
Before: