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.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

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

  4. Manoj says:

    Great explanation. Thank u so much ..

Leave a Reply


seven × = 28



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
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.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close