Java @ Desk: JSON | Java at your desk

Spring 4 Annotation Configuration without web.xml file using WebApplicationInitializer

Spring 4 Annotation Configuration without web.xml file using WebApplicationInitializer

Spring 4 allows annotation based configuration to initialize the web application without having the web.xml as well as spring configuration xml file. The spring controller and services are loaded using the annotation @ComponentScan.

With servlet 3.x there is no need of the spring configuration file defined in web.xml. Servlet 3.x allows annotation based loading of configuration classes for controllers and services.

Below example will load the controllers and services classes on server start up i.e. there will be a class to replace web.xml to map the Spring Dispatcher Servlet and load it on server start up. Rest controller example is implemented here that returns the JSON response to the caller.

pom.xml - Add Spring 4.x release and Servlet 3.x release to support annotation based loading of Dispatcher Servlet
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>Blogger</groupId>
 <artifactId>Blogger</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>war</packaging>
 <build>
  <finalName>blogger</finalName>
  <sourceDirectory>src</sourceDirectory>
  <plugins>
   <plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.5.1</version>
    <configuration>
     <source>1.8</source>
     <target>1.8</target>
    </configuration>
   </plugin>
   <plugin>
    <artifactId>maven-war-plugin</artifactId>
    <version>3.0.0</version>
    <configuration>
     <warSourceDirectory>WebContent</warSourceDirectory>
    </configuration>
   </plugin>
  </plugins>
 </build>
 <dependencies>
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>3.1.0</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>4.3.1.RELEASE</version>
  </dependency>
  <dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-databind</artifactId>
   <version>2.7.5</version>
  </dependency>
 </dependencies>
</project>


AppConfig.java - This class bootstrap Spring 4 MVC Rest in our application on server startup
package com.rest.spring4.annotationconfiguration.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.rest.spring4.annotationconfiguration")
public class AppConfig {

}


AppInitializer.java - This class is loaded by Servlet 3.x. This class will replace web.xml and it will map the spring’s dispatcher servlet and bootstrap it.
package com.rest.spring4.annotationconfiguration.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
 @Override
 protected Class[] getRootConfigClasses() {
  return new Class[] { AppConfig.class };
 }

 @Override
 protected Class[] getServletConfigClasses() {
  return null;
 }

 @Override
 protected String[] getServletMappings() {
  return new String[] { "/" };
 }
}




Person.java - Domain object for JSON response
package com.rest.spring4.annotationconfiguration.pojo;

public class Person {

 private String id;

 private String name;

 public String getId() {
  return id;
 }

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

 public String getName() {
  return name;
 }

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


PersonRestController.java - This class contains the Rest mapping to load the list of person objects in JSON format
package com.rest.spring4.annotationconfiguration.restcontroller;

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

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.rest.spring4.annotationconfiguration.pojo.Person;

@RestController
public class PersonRestController {

 @GetMapping("/persons")
 public ResponseEntity getPersons() {
  List<Person> persons = new ArrayList<Person>();

  Person person = new Person();
  person.setId("Id 1");
  person.setName("Person Name 1");

  persons.add(person);

  Person person2 = new Person();
  person2.setId("Id 2");
  person2.setName("Person Name 2");

  persons.add(person2);

  return new ResponseEntity(persons, HttpStatus.OK);
 }
}


Output:
[{"id":"Id 1","name":"Person Name 1"},{"id":"Id 2","name":"Person Name 2"}]

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"}