Alexey Zvolinskiy

About Alexey Zvolinskiy

Alexey is a test developer with solid experience in automation of web-applications using Java, TestNG and Selenium. He is so much into QA that even after work he provides training courses for junior QA engineers.

Spring MVC: Ajax & JQuery

Today I want to demonstrate how to integrate AJAX into a Spring MVC application. I’m going to use JQuery on a client side for sending of requests and receiving of responses. This tutorial will be based on one of my previous tutorials about Spring MVC and REST services. In this article you will read how to make a web-application more interactive with the help of asynchronous requests.

Preparations

I need to modify the SmartphoneController class by removing methods which are not required any more. This is a first step of AJAX integration.
 

//imports are omitted
@Controller
@RequestMapping(value="/smartphones")
public class SmartphoneController {

	@Autowired
	private SmartphoneService smartphoneService;

	@RequestMapping(value="/create", method=RequestMethod.GET)
	public ModelAndView createSmartphonePage() {
		ModelAndView mav = new ModelAndView("phones/new-phone");
		mav.addObject("sPhone", new Smartphone());
		return mav;
	}

	@RequestMapping(value="/create", method=RequestMethod.POST, 
			produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public Smartphone createSmartphone(@RequestBody Smartphone smartphone) {
		return smartphoneService.create(smartphone);
	}

	@RequestMapping(value="/edit/{id}", method=RequestMethod.GET)
	public ModelAndView editSmartphonePage(@PathVariable int id) {
		ModelAndView mav = new ModelAndView("phones/edit-phone");
		Smartphone smartphone = smartphoneService.get(id);
		mav.addObject("sPhone", smartphone);
		return mav;
	}

	@RequestMapping(value="/edit/{id}", method=RequestMethod.PUT, 
			produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public Smartphone editSmartphone(@PathVariable int id, 
			@RequestBody Smartphone smartphone) {
		smartphone.setId(id);
		return smartphoneService.update(smartphone);
	}

	@RequestMapping(value="/delete/{id}", method=RequestMethod.DELETE, 
			produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public Smartphone deleteSmartphone(@PathVariable int id) {
		return smartphoneService.delete(id);
	}

	@RequestMapping(value="", method=RequestMethod.GET,
			produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public List< Smartphone > allPhones() {
		return smartphoneService.getAll();
	}

	@RequestMapping(value="", method=RequestMethod.GET)
	public ModelAndView allPhonesPage() {
		ModelAndView mav = new ModelAndView("phones/all-phones");
		List< Smartphone > smartphones = new ArrayList< Smartphone >();
		smartphones.addAll(allPhones());
		mav.addObject("smartphones", smartphones);
		return mav;
	}

}

You can compare the new version of the SmartphoneController with the older one. Methods which process PUT, POST, DELETE requests and return ModelAndView objects were removed. The methods were deleted because AJAX calls can be addressed directly to REST methods. Now the controller contains just two types of methods:

  • The first type directs user to pages where CRUD operations can be performed.
  • The second type performs CRUD operations (REST methods)

Client side

An AJAX usage implies a lot of code on a client side of a web-application. In this section I will demonstrate a basics which will help you to understand what steps to do for implementation of AJAX calls. Let’s examine case with creation of a new smartphone in the application.

First of all I need to add JQuery library to HTML page:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

A main part of the HTML has one valuable update – extension of form action attribute was changed to .json

<div id="container">
<h1>Create new Smartphone</h1>
<div>
<p>Here you can create new Smartphone:</p>
<div id="sPhoneFromResponse"></div>
</div>
<form:form id="newSmartphoneForm" action="${pageContext.request.contextPath}/smartphones/create.json" commandname="sPhone">
<table>
<tbody>
<tr>
<td>Producer:</td>
<td>
<form:select path="producer">
	<form:option value="NOKIA">Nokia</form:option>
	<form:option selected="selected" value="IPHONE">iPhone</form:option>
	<form:option value="HTC">HTC</form:option>
	<form:option value="SAMSUNG">Samsung</form:option>
</form:select>
</td>
</tr>
<tr>
<td>Model:</td>
<td><form:input path="model"></form:input></td>
</tr>
<tr>
<td>Price:</td>
<td><form:input path="price"></form:input></td>
</tr>
<tr>
<td><input value="Create" type="submit"></td>
<td></td>
</tr>
</tbody>
</table>
</form:form>
<a href="${pageContext.request.contextPath}/index.html">Home page</a>
</div>

And now, ladies and gentlemen, I wish to introduce a snippet of JQuery code for the creation of new smartphone:

    $(document).ready(function() {

      $('#newSmartphoneForm').submit(function(event) {

    	  var producer = $('#producer').val();
    	  var model = $('#model').val();
    	  var price = $('#price').val();
    	  var json = { "producer" : producer, "model" : model, "price": price};

        $.ajax({
        	url: $("#newSmartphoneForm").attr( "action"),
        	data: JSON.stringify(json),
        	type: "POST",

        	beforeSend: function(xhr) {
        		xhr.setRequestHeader("Accept", "application/json");
        		xhr.setRequestHeader("Content-Type", "application/json");
        	},
        	success: function(smartphone) {
        		var respContent = "";

		  		respContent += "<span class="success">Smartphone was created: [";
		  		respContent += smartphone.producer + " : ";
		  		respContent += smartphone.model + " : " ;
		  		respContent += smartphone.price + "]</span>";

        		$("#sPhoneFromResponse").html(respContent);   		
        	}
        });

        event.preventDefault();
      });

    });

I’m not going to stop on this code and explain it in detail because you can read about AJAX and JQuery on official site.

Brief explanation: when someone want to submit the form with specified ID, all form fields are assigned to appropriate variables. After that a new JSON document is generated based on the form field variables. Then AJAX call is performed. It directed to URL which is specified in the action attribute of form tag. The JSON is used as a data which need to be processed. Type of the request is POST (it can vary depending on operation, e.g. for update it will has PUT value). In the beforeSend function I explicitly specify required headers for JSON format. In the end I formulate a response and insert it in DOM.

Create-new-Smartphone

That’s it what related to creation of smartphone. The update of smartphone is the similar, just type of the request need to be changed.

Now let’s see how to work with DELETE type of requests. As previously I need to change extension of URLs to .json

<a href="${pageContext.request.contextPath}/smartphones/delete/${sPhone.id}.json">Delete</a>

A JQuery code for the DELETE operation will be a little bit distinct compared to POST and PUT.

$(document).ready(function() {

	var deleteLink = $("a:contains('Delete')");

	$(deleteLink).click(function(event) {

		$.ajax({
			url: $(event.target).attr("href"),
			type: "DELETE",

			  beforeSend: function(xhr) {
			  	xhr.setRequestHeader("Accept", "application/json");
			  	xhr.setRequestHeader("Content-Type", "application/json");
			  },

			  success: function(smartphone) {
			  	var respContent = "";
			  	var rowToDelete = $(event.target).closest("tr");

			  	rowToDelete.remove();

			  	respContent += "<span class="success">Smartphone was deleted: [";
			  	respContent += smartphone.producer + " : ";
			  	respContent += smartphone.model + " : " ;
			  	respContent += smartphone.price + "]</span>";

			  	$("#sPhoneFromResponse").html(respContent);   		
			  }
		});

		event.preventDefault();
	});

});

The first distinction is the selector for the element. In case with DELETE I want to work with links but not with forms. The type of the AJAX call is changed to DELETE value. There is no any data which is send with the request. And in the end I delete the row with the smartphone which need to be deleted.

Delete-smartphone

Summary

I hope this short overview of the AJAX will be useful for you. There are a lot of features which can be implemented with the help of AJAX in any web-application, so don’t ignore this convenient way for communication with a server. You can find this application on GitHub.
 

Reference: Spring MVC: Ajax & JQuery from our JCG partner Alexey Zvolinskiy at the Fruzenshtein’s notes blog.
Related Whitepaper:

Introduction to Web Applications Development

Kick start your web apps development with this introductory ebook!

This 376 page eBook 'Introduction to Web Applications Development', starts with an introduction to the internet, including a brief history of the TCT/IP protocol and World Wide Web. It defines the basic concepts for web servers and studies the case of Apache, the most used webserver, while other free software webservers are not forgotten. It continues with webpage design focusing on HTML and JavaScript. XML Schemas, their validation and transformation are covered as well as dynamic webpages built with CGI, PHP or JSP and database access.

Get it Now!  

3 Responses to "Spring MVC: Ajax & JQuery"

  1. alonso says:

    thanks for sharing the code

  2. Yop says:

    Hi,
    it’s a sample too complex

  3. amaresh says:

    I have a doubt.

    If at all I need to send HttpServletRequest and HttpServletResponse in the following method.
    How do I send?

    public Smartphone deleteSmartphone(@PathVariable int id)

Leave a Reply


8 + = fifteen



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books