Java @ Desk: Ajax | Java at your desk

Angular JS Spring MVC Rest CRUD JSON Example using $http

Angular JS Spring MVC Rest CRUD JSON Example using $http

In this example, we will learn how to get the json data from rest service controller from Spring and display using the ng-model attribute of angular JS.

Spring RestController returns the Customer java object in JSON format and data is displayed on UI using angular JS. Call to the rest api is done using the $http of angular JS.

Following components will be used
1) Spring RestController
2) Angular JS ng-app
3) Angular JS ng-controller
4) Angular JS ng-model
5) Angular JS $http

Here are the files that are used.

Customer.java
package com.accenture.restviability.pojo;

public class Customer {

 private String name;
 
 private String id;

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getId() {
  return id;
 }

 public void setId(String id) {
  this.id = id;
 }
}


SpringRestController
package com.accenture.restviability.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.accenture.restviability.pojo.Customer;
import com.google.gson.Gson;

@RestController()
@CrossOrigin(maxAge = 3600)
public class SpringRestController {

 @RequestMapping(method = RequestMethod.GET, path = "/customers", produces = MediaType.APPLICATION_JSON_VALUE)
 public ResponseEntity<Customer> getCustomers() {
  System.out.println("Entered in Get Customers");
  List<Customer> customers = new ArrayList<Customer>();
  Customer customer = new Customer();
  customer.setName("Kumar");
  customer.setId("1");
  Gson gson = new Gson();
  return new ResponseEntity<Customer>(customer, HttpStatus.OK);
 }
}




customer.jsp
<!DOCTYPE html>
<html ng-app="customerApp">
<head>
<title>Customer App</title>
<script src="js/angular.js"></script>
<script src="js/customerController.js"></script>
<script src="js/jquery.min.js"></script>
</head>

<body>
 <div ng-controller="customerController">
  <p>
   Customer Id - <input type="text" ng-model="customer.id" />
  </p>
  <p>
   Customer Name - <input type="text" ng-model="customer.name" />
  </p>
 </div>
</body>
</html>


customerController.js
var app = angular.module('customerApp', []);
app.controller("customerController", function($scope, $http) {
 $http.get('http://localhost:8070/customers').then(
   function successCallback(response) {
          $scope.customer = {name: response.data.name, id: response.data.id};
   }, function errorCallback(response) {
   });
});


Jquery pass Json data from HTML to Servlet in Ajax

Jquery pass Json data from HTML to Servlet in Ajax

In order to pass JSON data from HTML to servlet, javascript object is created and values are set into user defined properties of the object. Data is passed in String json format using JSON.stringify(jsonData).

Data is passed using the data attribute of ajax service.

Below example is to illustrate the same. Value of a textbox is passed to a servlet in JSON String format.

HTML File:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery.min.js"></script>
<script src="js/common.js"></script>
<script src="js/jquery-ui.min.js"></script>

</head>
<body>
 <form id="inputform">
  <div style="height: 40px;"></div>

  <input type="text" id="textBox" name="textBox"> <input
   type="button" value="Identify" onclick="submitJsonPostData()" />
 </form>
</body>
</html>


JS File:
function submitJsonPostData() {
 var text = $("#textBox").val();
 var jsonData = new Object();
 jsonData.text = text;
 $.ajax({
  url : 'JsonPostDataServlet',
  type : 'POST',
  data : {
   jsonPostRequest : JSON.stringify(jsonData)
  },
  success : function(response) {
  },
  error : function(response) {
   alert("Error: Timeout please try again later");
  },
 });
}




Servlet:
package com.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/JsonPostDataServlet")
public class JsonPostDataServlet extends HttpServlet {
 @SuppressWarnings("unchecked")
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  String jsonPostRequest = request.getParameter("jsonPostRequest");
  System.out.println("Json Post Request received from JSP - " + jsonPostRequest);
 }
}


Output:
Json Post Request received from JSP -
{"text":"TextValue"}

Ajax json jquery Post example

Ajax json jquery Post example

Ajax is used to update the parts of the web page with out reloading the entire page.

JSON is used to store and exchange the data between client and server.

Enums is used to store the data means a list of named constants.

In this example, Data will be loaded into drop down list based on the selected option(country) using Jquery and the above mentioned technologies.

Unlike JSP's , we can make use of HTML itself by using JSON concept for data exchange between client and server.

In this example, Dynamic data loading is shown by using drop down list, Code has flexibility to extend to other elements of a web page. Whenever Country option has selected OnChange event will be triggered and it in turn calls the specified function, In this example it was callRegCountry(), which has Ajax call (Asynchronous JavaScript and XML.) nothing but a replacement of Form submit in a better way.

Ajax and its terms:

type : Type of request eg: get, post
url : The URL to which the request has to sent,Typically Servlet or JSP.
data : An object or string that is sent to the server with the request.
Success : A callback function that is executed if the request succeeds.
Error : function called When request completes with an error

HTML Code:

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>AJAX-JSON example</title>
<meta name="description"
 content="Dynamic Loading of data by Ajax via JSON and enums">
<meta name="author" content="sekhar">

<!-- jquery.js is loaded through Google CDN-->

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

<!-- JSON2.js needed if IE versions less than IE8 -->

<script src="json2.js"></script>

<script>

// Will be triggered when country name was changed

function callRegCountry(){

 var countryName=$('#countryRows').val();//Will Get Selected Country

  $('#cityRows option:gt(0)').remove();//For removing old entries in city drop down.Since Ajax won't reload page.

 $.ajax({
  type : "POST",//request type
  url : "/AjaxJson/ControllerServlet",//Servlet name ..can be configured through web.xml
  data : {
   "flag":"retCities",//flag--to distinguish from multiple requests
        "country":countryName
  },

  dataType : "text",
  success : function(data) {
   try{
    var citiArray=JSON.parse(data);

    if(citiArray != null){

    for(var s=0;s<citiArray.length;s++){

    var serial=citiArray[s];
    //populating drop down list
       $("#cityRows").append($("<option></option>").val(serial.city).html(serial.city));
    }
    }
    }catch(err){
     alert(err);
    }

   },
   error : function(){
    alert("some error occured while fetching city details corresponding to county "+countryName);
   }
  
  });
}

</script>
</head>
<body>
 <div id="loader">
 <div id="Country_loader">
  <table>
   <tr>
    <td width="250px"><label>Choose the Country</label></td>
    <td><select id="countryRows" onchange="callRegCountry()">
     <option value="india">India</option>
     <option value="america">America</option>
           </select>
    </td>
   </tr>
  </table>
 </div>
 <div id="Citi_loader">
  <table>
   <tr>
    <td width="250px"><label>Corresponding Cities</label></td>
    <td><select id="cityRows">
    <option value="-1">-Choose-</option>
     </select></td>
   
   </tr>
  </table>
 </div>
 </div>
</body>
</html>


Ajax Request will call servlet post method, Flag was used to separate from multiple requests. Based on that it will call corresponding method in java.

Servlet Code



protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
 response.setContentType("text/html");
 String flag=request.getParameter("flag");
 BusinessHandler handler=new BusinessHandler();
 if(flag.equalsIgnoreCase("retCities")){
  try {
   handler.retCities(request,response);
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}


In this code fragment,Used two enumerations to hold the data,instead of getting data from Database. Here based on selected country ,iterating the corresponding enumeration and creating JSON object and adding that to JSON array and sending the JSON array as a response.

Java Code:

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

enum India{
 Mumbai,Hyderabad,Chennai,Delhi,Bangalore;
}
enum America{
 Mexico,NewYork,Toronto,Chicago;
}

public class BusinessHandler {
 //Based on the selected country in front end corresponding enumeration will be iterated.enumeration is nothing but a list of constants. 

public void retCities(HttpServletRequest request, HttpServletResponse response) throws Exception {
 String country=request.getParameter("country");//holds selected country
JSONArray citArray=new JSONArray();
if(country.equalsIgnoreCase("india")){
      for(India cnt:India.values()){//iterating India enum
   JSONObject citObject=new JSONObject();
   citObject.put("city", cnt);//populating JSONobject
    citArray.add(citObject);
  }
} else {
for(America cnt:America.values()){
JSONObject citObject=new JSONObject();
   citObject.put("city", cnt);
   citArray.add(citObject);
}
}
 response.getWriter().write(citArray.toString());
}
}


jar files used for smooth flow:

ezmorph.jar
json-lib-2.2.2-jdk15.jar
commons-beanutils-1.7.jar
commons-collections.jar
commons-lang.jar
commons-logging-1.1.1.jar

Server used:

Apache tomcat v7.0