Spring 4 RESTful webservice Hello World & JSON response example

In this tutorial, let us see how to create Hello World Restful webservice in Spring 4 in eclipse without using Maven. Spring provides a built-in support for restful service. It is very simple to create restful webservice in Spring. In this tutorial, let us create two services

1. HelloWorldService: this service accepts request parameter “name” and returns a response “Hello<name> ” as String. The name can be passed as request parameter or path variable.

2. GetProductDetailsService : this service accepts “itemcode” and returns  response with item details and price as JSON. For returning JSON, we will use Jackson java library in this example which converts Object (POJO) to JSON and Vice versa. The itemcode is passed as request parameter or path variable.

Technology & Jars Used:

JDK 1.8

Spring 4.0 or above

jackson-annotations-2.5.4.jar

jackson-core-2.2.0.jar

jackson-databind-2.1.4.jar

Eclipse IDE

Tomcat v7.0

Annotations used :

i) @RestController:

In Spring RESTful web services, HTTP requests are handled by a controller. To make a java class as controller for handling restful webservice, just add @RestController annotation just above the class definition.

@RequestMapping:

The @RequestMapping annotation maps the HTTP requests with a java class ( controller i.e handler classes) and/or any java methods.

@PathVariable: Retrieves some value from the uri (excludes base URI i.e.  http://localhost:8080/SpringRestService/hello)  and maps to the path variable.  The below code explains about @PathVariable annotation.

http://localhost:8080/SpringRestService/hello/John/Paul

@RestController
@RequestMapping("/hello")
public class HelloWorldService {
   @RequestMapping(value = "/{firstName}/{lastName}", method = RequestMethod.GET)
   	public String helloMethod2(@PathVariable String firstName, @PathVariable String lastName)    {
    ...
    ..}
   }

In the above url, the value John is mapped to path variable firstName and Paul is mapped to lastName

@RequestParam: The @RequestParam binds request parameter to the corresponding method parameter in the controller.

http://localhost:8080/SpringRestService/getProduct?itemcode=1

@ResponseBody: To convert any method’s returned object to JSON or any other formats like XML, text, etc.., the method may be annotated with @ResponseBody. Spring converts the returned object to other formats (i.e JSON,etc..) by using an HttpMessageConverter. @ResponseBody also indicates that the return data is written to the body of response.

In this example, HttpMessageConverter is implemented by Jackson2MessageConvertor that can convert return object to JSON and vice versa using Jackson 2.x’s ObjectMapper.

To configure bean to convert JSON to Object and vice versa, the following lines are used in the rest-servlet.xml which will have REST related configuration.  rest is the servlet name  of servlet class of org.springframework.web.servlet.DispatcherServlet in web.xml

   <!-- for processing requests with annotated controller methods and set Message Convertors from the list of convertors -->
    <beans:bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <beans:property name="messageConverters">
            <beans:list>
                <beans:ref bean="jsonMessageConverter"/>
            </beans:list>
        </beans:property>
    </beans:bean>

    <!-- To  convert JSON to Object and vice versa -->
    <beans:bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    </beans:bean>

Complete rest-servlet.xml is given at the end of this tutorial.

Now let us create two restful web services (HelloWorldService & GetProductDetailsService) with Spring 4 in Eclipse without maven.

1. Create a Dynamic Web Project (SpringRestService)

spring rest ws1 spring rest ws2 spring rest ws3

Final Project Directory Structure:

Spring Restful service directory structure Spring Restful service directory structure1

2. Create model (POJO) for ProductDetails


 package net.javaonline.spring.restful.model;

public class ProductDetails {

	String itemcode="";
	String description="";
	float MRP=0;
	float itemprice=0;
	float discount=0;

	public ProductDetails(String itemcode,String description, float MRP,  float discount)
		{
			this.itemcode=itemcode;

			this.description=description;

			this.MRP=MRP;

			this.itemprice=MRP-discount;

			this.discount=discount;

		}

	public String getItemcode() {
		return itemcode;
	}
	public void setItemcode(String itemcode) {
		this.itemcode = itemcode;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	public float getMRP() {
		return MRP;
	}
	public void setMRP(float mRP) {
		MRP = mRP;
	}
	public float getItemprice() {
		return itemprice;
	}
	public void setItemprice(float itemprice) {
		this.itemprice = itemprice;
	}
	public float getDiscount() {
		return discount;
	}
	public void setDiscount(float discount) {
		this.discount = discount;
	}

}

3. Create HelloWorldService and GetProductService controller

HelloWorldService.java

package net.javaonline.spring.restful.controller;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/hello")
public class HelloWorldService {

	@RequestMapping
    public String helloMethod1(@RequestParam(value="name", defaultValue="World") String name) {

    	  return   "Hello  "+ name;
    }

	@RequestMapping(value = "/{firstName}/{lastName}", method = RequestMethod.GET)
   	public String helloMethod2(@PathVariable String firstName, @PathVariable String lastName) {
   		return "Hello "+ firstName + " " + lastName;
    	}    

}

GetProductService.java

package net.javaonline.spring.restful.controller;

import net.javaonline.spring.restful.dao.GetProductDetailsDAO;
import net.javaonline.spring.restful.model.ProductDetails;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GetProductDetailsService {

    @RequestMapping("/getProduct")
    public @ResponseBody ProductDetails getProductMethod1(@RequestParam(value="itemcode", defaultValue="1") String itemcode) {
    	GetProductDetailsDAO pdDao=new GetProductDetailsDAO();
    	  return  pdDao.getProductDetails(itemcode);
    }

    @RequestMapping("/getProduct/{itemcode}")
    public @ResponseBody ProductDetails getProductMethod2(@PathVariable(value="itemcode")  String itemcode) {
    	GetProductDetailsDAO pdDao=new GetProductDetailsDAO();
    	  return  pdDao.getProductDetails(itemcode);
    }

}

GetProductDetailsDAO.java //to retrieve item details

package net.javaonline.spring.restful.dao;

import java.util.HashMap;
import java.util.Map;

import net.javaonline.spring.restful.model.ProductDetails;

public class GetProductDetailsDAO {

	Map<String, ProductDetails> products = new HashMap<String, ProductDetails>();

	public GetProductDetailsDAO()
	{

		//product details to be retrieved from the database. 

		products.put("1", new ProductDetails("1", "LCD TV", 60000, 4000));
		products.put("2", new ProductDetails("2", "LED TV", 70000, 5000));
		products.put("3", new ProductDetails("3", "AC", 40000, 3000));
		products.put("4", new ProductDetails("4", "Laptop", 50000, 1000));

	}

	public ProductDetails getProductDetails(String itemcode)
	{

		return products.get(itemcode);

	}

}

In the second example i.e GetProductDetails service accepts itemcode and returns JSON as response.

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>SpringRestFulService</display-name>

<servlet>
	<servlet-name>rest</servlet-name>
	<servlet-class>
		org.springframework.web.servlet.DispatcherServlet
	</servlet-class>
	<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
	<servlet-name>rest</servlet-name>
	<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>

rest-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- Enables the Spring MVC @Controller programming model -->
    <annotation-driven />

   <!-- for processing requests with annotated controller methods and set Message Convertors from the list of convertors -->
    <beans:bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <beans:property name="messageConverters">
            <beans:list>
                <beans:ref bean="jsonMessageConverter"/>
            </beans:list>
        </beans:property>
    </beans:bean>

    <!-- To  convert JSON to Object and vice versa -->
    <beans:bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    </beans:bean> 

    <context:component-scan base-package="net.javaonline.spring.restful" />

</beans:beans>

For accessing the services :

HelloWorldService

http://localhost:8080/SpringRestService/hello?name=Jegan%20kumar

http://localhost:8080/SpringRestService/hello/Jegan/kumar

Output:

spring rest ws output1

GetProductDetailsService

http://localhost:8080/SpringRestService/getProduct

http://localhost:8080/SpringRestService/getProduct?itemcode=1

Output JSON:

spring rest ws output2

Default value for itemcode is 1 if it is not passed.

 

http://localhost:8080/SpringRestService/getProduct/4/

spring rest ws output3

Reference :  Building a RESTful Web Service in Spring

You can download the above spring webservice application including jar files at

Leave a Reply

top 10 dietary supplements for weight loss keto flex diet recipes keto tone diet pills review no carb diet how much weight loss keto diet recipes casserole fast weight loss pills only bought in usa how to lose weight without dieting lose weight diet drinks with fennel best lose weight fast diets perricone weight loss diet menu how can i change my diet to lose weight quickest diet to lose weight in a week will keto pills alone help me lose weight safe weight loss diet weight loss on slim fast diet weight loss success on diabetic diet weight loss diet plan for summer cleanse for weight loss pills vivus weight loss pill taking hormone pills to lose weight vegan diet for a week weight loss rp diet weight loss quick weight loss center houston supplements steamed food diet weight loss best weight loss pills skald liquid diet before and after weight loss most effective legal weight loss pills hours between taking green tea weight loss pills image healthy weight loss pills which is a good diet to lose weight redit mango weight loss diet nutri burn weight loss pills ketogenic diet for weight loss made simple how does weight loss occur using the dukan diet iron pills lose weight really effective weight loss pills

cbd oil for wrinkles before and after glaucoma cbd oil cbd tinctures for sale happy life cbd oil diamond cbd drug test coconut cbd oil honey oil cbd 5 cbd oil does cbd affect menstrual cycle cbd tincture with thc overdose cbd cbd oil roll on for pain cbd oil 10000 mg cbd oil where to buy near me cbd oil dosage for nausea cbd for horses does cbd oil test positive for thc does cbd oil have expiration date how to smoke cbd isolate cbd that gets you high restless leg syndrome cbd empire extracts cbd hemp flower medical effects of cbd cbd for tension headaches cachet cbd oil reviews cbd college review renew cbd cream cbd oil for skin rash cbd dispensary virginia cbd oil effects anxiety car parking sydney cbd cbd oil products what should i pay for cbd oil real cbd oil online cookies made with cbd oil can i acquire cbd oil

prosolution pills illegal male enhancement pills sold in stores top 10 ed pills penis enlargement bed techniques breast enhancement male hims pills anamax male enhancement ed pills and tylenol poseidon male enhancement review ed pills store pns king male enhancement how to wear a penis enlargement device penis enlargement tricks penis enlargement tequnic penis enlargement myth next day pill cvs price penis enlargement vape pro solutions pills erectile dysfunction pills silfill red penis pills ght male supplement cigna coverage penis enlargement the black pill extenze sex pills for paraplegics male enhancement pill by natural way sex penis male enhancement pill bigger longer penis enlargement aquaman alibaba tablet sex pills at corner stores estrogen natural supplements progestrone supplement sex drive penis enlargement explained male enhancement supplement pills male enhancement from shark tank before and after penis enlargement pills how to get a bigger penis size without pills