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)
Image may be NSFW.
Clik here to view. Image may be NSFW.
Clik here to view. Image may be NSFW.
Clik here to view.
Final Project Directory Structure:
Image may be NSFW.
Clik here to view. Image may be NSFW.
Clik here to view.
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:
Image may be NSFW.
Clik here to view.
GetProductDetailsService
http://localhost:8080/SpringRestService/getProduct
http://localhost:8080/SpringRestService/getProduct?itemcode=1
Output JSON:
Image may be NSFW.
Clik here to view.
Default value for itemcode is 1 if it is not passed.
http://localhost:8080/SpringRestService/getProduct/4/
Image may be NSFW.
Clik here to view.
Reference : Building a RESTful Web Service in Spring
You can download the above spring webservice application including jar files at
Clik here to view.
