Ajax (Asynchronous JavaScript and XML) is a web development technique used on the client side to create asynchronous web applications. In a typical web application, every time a web request is fired as a response, we get a full web page loaded, but in an Ajax-based web application web pages are updated asynchronously by polling small data with the server behind the scenes. This means that, using Ajax, it is possible to update parts of a web page without reloading the entire web page. With Ajax, web applications can send data to, and retrieve data from, a server asynchronously. The asynchronous aspect of Ajax allows us to write code that can send some requests to a server and handles a server response without reloading the entire web page.
In an Ajax-based application, the XMLHttpRequest
object is used to exchange data asynchronously with the server, whereas XML or JSON is often used as the format for transferring data. The "X" in AJAX stands for XML, but JSON is used instead of XML nowadays because of its simplicity, and it uses fewer characters to represent the same data compared to XML. So it can reduce the bandwidth requirements over the network to make the data transfer speed faster.
Okay, we have implemented some REST-based web services that can manage the shopping cart in our application, but we need a frontend that can facilitate the end user to manage a shopping cart visually. So let's consume those web services via Ajax in the frontend to manage the shopping cart. In order to consume REST web services via Ajax, perform the following steps:
controllers.js
under the directory /src/main/webapp/resources/js/
, add the following code snippets into it, and save it:var cartApp = angular.module('cartApp', []); cartApp.controller('cartCtrl', function($scope, $http) { $scope.refreshCart = function(cartId) { $http.get('/webstore/rest/cart/' + $scope.cartId) .success(function(data) { $scope.cart = data; }); }; $scope.clearCart = function() { $http.delete('/webstore/rest/cart/' + $scope.cartId) .success(function(data) { $scope.refreshCart($scope.cartId); }); }; $scope.initCartId = function(cartId) { $scope.cartId = cartId; $scope.refreshCart($scope.cartId); }; $scope.addToCart = function(productId) { $http.put('/webstore/rest/cart/add/' + productId) .success(function(data) { alert("Product Successfully added to the Cart!"); }); }; $scope.removeFromCart = function(productId) { $http.put('/webstore/rest/cart/remove/' + productId) .success(function(data) { $scope.refreshCart($scope.cartId); }); }; });
CartController
under the package com.packt.webstore.controller
in the source folder src/main/java
and add the following code into it:package com.packt.webstore.controller; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind .annotation.PathVariable; import org.springframework.web.bind .annotation.RequestMapping; import org.springframework.web.bind .annotation.RequestMethod; @Controller @RequestMapping(value = "/cart") public class CartController { @RequestMapping public String get(HttpServletRequest request) { return "redirect:/cart/"+request.getSession(true).getId(); } @RequestMapping(value = "/{cartId}", method = RequestMethod.GET) public String getCart(@PathVariable(value = "cartId") String cartId, Model model) { model.addAttribute("cartId",cartId); return "cart"; } }
cart.jsp
under the directory src/main/webapp/WEB-INF/views/
, add the following code snippets into it, and save it:<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <link rel="stylesheet" href="//netdna.bootstrapcdn.com/ bootstrap/3.0.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax /libs/angularjs/1.5.1/angular.min.js"></script> <script src="/webstore/resources/js/ controllers.js"></script> <title>Cart</title> </head> <body> <section> <div class="jumbotron"> <div class="container"> <h1>Cart</h1> <p>All the selected products in your cart</p> </div> </div> </section> <section class="container" ng-app="cartApp"> <div ng-controller="cartCtrl" ng- init="initCartId('${cartId}')"> <div> <a class="btn btn-danger pull-left" ng-click="clearCart()"> <span class="glyphicon glyphicon-remove- sign"></span> Clear Cart </a> <a href="#" class="btn btn-success pull-right"> <span class="glyphicon-shopping-cart glyphicon"></span> Check out </a> </div> <table class="table table-hover"> <tr> <th>Product</th> <th>Unit price</th> <th>Qauntity</th> <th>Price</th> <th>Action</th> </tr> <tr ng-repeat="item in cart.cartItems"> <td>{{item.product.productId}}- {{item.product.name}}</td> <td>{{item.product.unitPrice}}</td> <td>{{item.quantity}}</td> <td>{{item.totalPrice}}</td> <td><a href="#" class="label label- danger" ng- click="removeFromCart(item.product.productId)"> <span class="glyphicon glyphicon- remove" /></span> Remove </a></td> </tr> <tr> <th></th> <th></th> <th>Grand Total</th> <th>{{cart.grandTotal}}</th> <th></th> </tr> </table> <a href="<spring:url value="/market/products" />" class="btn btn-default"> <span class="glyphicon-hand-left glyphicon"></span> Continue shopping </a> </div> </section> </body> </html>
product.jsp
from src/main/webapp/WEB-INF/views/
and add the following AngularJS-related script links in the head section as follows:<script src="https://ajax.googleapis.com/ajax /libs/angularjs/1.5.5/angular.min.js"></script>
controller.js
as follows:<script src="/webstore/resources /js/controllers.js"></script>
ng-click
AngularJS directive to the Order Now <a>
tag as follows: <a href="#" class="btn btn-warning btn-large" ng-
click="addToCart('${product.productId}')">
<span class="glyphicon-shopping-cart
glyphicon"></span> Order Now
</a>
<a>
tag beside the Order Now <a>
tag, which will show the View cart button and save the product.jsp
:<a href="<spring:url value="/cart" />" class="btn btn-default"> <span class="glyphicon-hand-right glyphicon"></span> View Cart </a>
ng-app
AngularJS directive to the Order Now <section>
tag as follows: <section class="container" ng-app="cartApp">
ng-controller
AngularJS directive to the surrounding <p>
tag of the Order Now
link as follows: <p ng-controller="cartCtrl">
http://localhost:8080/webstore/market/product?id=P1234
. You should be able to see the product detail page of a product whose ID is P1234.