Home > Spring 4

Spring 4 + Rest Web Service + JSON Example with Tomcat

June 18, 2014
In this page we will learn how to use Spring 4 with REST Web Service to get JSON response. A Spring 4 Web Service class is annotated with @RestController that replaces the use of @Controller and @ResponseBody. To map the REST Web Service URL, use the annotation @RequestMapping. Web service method argument contains @RequestParam that has the attribute defaultValue that will assign a default value for request parameter whose value is not available in request.
To setup the environment, we can use Spring Boot for fast startup. WebApplicationInitializer is being used to replace web.xml settings. Spring configuration will be initialized by WebApplicationInitializer while on server startup.

Software Used

Below softwares are needed to develop our Spring 4 + Rest Web Service + JSON Example.

1. Eclipse
2. Java 6
3. Tomcat 7

Setup Spring 4 Environment Using Spring Boot with Maven

Spring Boot is the combination of Jar and Tomcat server. Spring Boot fetches all Jars required to run Spring 4 application. For developers, Spring Boot makes it easy to start development in easy and fast way. Spring Boot can be used with Gradle 1.11 or Maven 3.0. In our demo project we have used maven.
In our demo, we have a separate tomcat in which we deploy our WAR file externally. For JSON, Jackson API will be used. For Jackson dependency jackson-databind is used. Find the maven dependency.
pom.xml
      <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.1.1.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
    </dependencies>     

Create Configuration Class and WebApplicationInitializer ( without web.xml)

Spring configuration will not use XML approach. @Configuration supports a class to define the spring configuration for component and beans used in the application.
AppConfig.java
package com.concretepage.config;  
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@Configuration 
@ComponentScan("com.concretepage") 
@EnableWebMvc   
public class AppConfig {  
} 
In servlet 3.0, now java web application has capability to run its application without using web.xml. In spring 3.1 onwards WebApplicationInitializer is used in place of web.xml and continue to Spring 4. In our demo all the web setting will be done in a class which will implement WebApplicationInitializer.
On startup, server looks for WebApplicationInitializer. If server finds it in the application, then server starts the application using the settings defined in WebApplicationInitializer implementing class.
WebAppInitializer.java
package com.concretepage.config;
import javax.servlet.ServletContext;  
import javax.servlet.ServletException;  
import javax.servlet.ServletRegistration.Dynamic;  
import org.springframework.web.WebApplicationInitializer;  
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;  
import org.springframework.web.servlet.DispatcherServlet;  
public class WebAppInitializer implements WebApplicationInitializer {
	public void onStartup(ServletContext servletContext) throws ServletException {  
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();  
        ctx.register(AppConfig.class);  
        ctx.setServletContext(servletContext);    
        Dynamic dynamic = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));  
        dynamic.addMapping("/");  
        dynamic.setLoadOnStartup(1);  
   }  
} 

Create Component

We have created a sample component for the example. This has a method that will return an object Person which will be changed in JSON format in response.
Find the Person class which will be retuned as JSON response.
Person.java
package com.concretepage;
public class Person {
	private int id;
	private String location;
	private String name;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getLocation() {
		return location;
	}
	public void setLocation(String location) {
		this.location = location;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

} 
Find the interface for component class.
IPersonService.java
package com.concretepage.component;
import com.concretepage.Person;
public interface IPersonService {
  public Person getPersonDetail(Integer id);
} 
Implement the method of interface.
PersonService.java
package com.concretepage.component;
import org.springframework.stereotype.Component;
import com.concretepage.Person;
@Component
public class PersonService implements IPersonService {
	@Override
	public Person getPersonDetail(Integer id){
		Person p = new Person();
		p.setId(id);
		p.setLocation("Varanasi");
		p.setName("Ram");
		return p;
	}
} 

Create Controller Class Using @RestController

Finally we implement our web service class which will be exposed for rest service. The class will be annotated with @RestController . Spring 4 has introduced @RestController annotation to replace @Controller and @ResponseBody. The annotation @RequestMapping can be used at class level as well as method level for Rest Web Service URL mapping.
PersonController.java
package com.concretepage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.concretepage.component.IPersonService;
@RestController
@RequestMapping("/data")
public class PersonController {
	@Autowired
	private IPersonService personService;
	@RequestMapping("/person")
	public Person getPersonDetail(@RequestParam(value = "id",required = false,
	                                                    defaultValue = "0") Integer id) {
		Person p = personService.getPersonDetail(id);
		return p;
	}
} 

Eclipse Configuration for the Spring 4 Demo Project

Find the image view how the classes has been configured in eclipse for our spring 4 demo.
Spring 4 + Rest Web Service + JSON Example with Tomcat

Output of Demo Project

Run the pom.xml. Deploy war in Tomcat and hit the URL as http://localhost:8080/Spring4-1/data/person?id=15 Below output will be displayed.
Spring 4 + Rest Web Service + JSON Example with Tomcat

Download Source Code


comments powered by Disqus


Home    Core Java    Spring    Hibernate    Jquery    My Computer    News    Forum    Quiz    Interview Q & A     Maven     Eclipse IDE

Copyright ©2014 concretepage.com | All rights reserved |Privacy