In
this tutorial, let us see how to create Hello World Restful web service in
Spring 4 in eclipse without using Maven.
What
is REST?
REST (REpresentational
State Transfer) is an architectural style, and an approach to
communications that is usually used when developing Web services. REST has
gained in popularity over its contender SOAP (Simple Object Access Protocol)
because REST is lighter in terms of bandwidth usage. RESTful services are much
easier to implement and scale than SOAP. Thus REST is the chosen architecture
by service providers like Facebook, Twitter, Amazon,
Microsoft, and Google.
REST
architecture describes six constraints. These constraints were described in Roy Fielding’s dissertation as Uniform
Interface, Stateless, Cacheable, Client-Server, Layered-System, and Code On
Demand.
- Uniform Interface –
Resources are manipulated via CRUD (create, read, update, delete)
operations. CRUD operations are managed via PUT, GET, POST, and DELETE
request methods.
- Stateless –
In REST the state is contained within the request itself, or as part of
the URI, query-string parameters, body or in the headers. After processing
the request, the state may be communicated back via the headers, status or
response body.
- Cacheable –
Responses from the web service to its clients are explicitly labeled as
cacheable or non-cacheable. This way, the service, the consumer, or one of
the intermediary middleware components can cache the response for reuse in
later requests.
- Client Server –
This is a key constraint, as it based on separations of concerns. The
client/server requirement ensures that a distributed environment exists.
It requires the client, that sends requests and a server component that
receives the requests. After processing the request, the server may return
a response to the client. Error responses may be transmitted as well,
which requires the client to be responsible for taking any corrective
action.
- Layered System –
A client should may not be able to tell whether it is connected directly
to the end server, or to an intermediary along the way. Intermediary
servers may add security policies, or improve scalability.
- Code On Demand –
This is an optional constraint. It allows a client to have logic locally
via the ability to download and execute code from a remote server.
RESTful
Web Services for CRUD Operations
RESTFul
web services define the base URI (Universal Resource Identifier) for the web
service, it also defines the end points of the service via links on the web.
Resources are manipulated via CRUD (create, read, update, delete) operations.
CRUD operations are managed via PUT, GET, POST, and DELETE request methods.
Spring
provides a built-in support for restful service. It is very simple to create
restful web service in Spring. In this tutorial, let us create two services
1. HelloWorldService: this
service accepts request parameter “name” and returns a response
“Hello ” 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.
@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 Jackson2MessageConvertorthat 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
<
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
>
<
beans:bean
id
=
"jsonMessageConverter"
class
=
"org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"
>
</
beans:bean
>
Now
let us create two restful web services (HelloWorldService &
GetProductDetailsService) with Spring 4 in Eclipse without maven.
1. Create
a Dynamic Web Project (SpringRestService)
2. Create
model (POJO) for ProductDetails
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
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
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
import
java.util.HashMap;
import
java.util.Map;
public
class GetProductDetailsDAO {
Map products
= new HashMap();
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">
<
annotation-driven
/>
<
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
>
<
beans:bean
id
=
"jsonMessageConverter"
class
=
"org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"
>
</
beans:bean
>
<
context:component-scan
base-package
=
"com.teachtojava.spring.restful"
/>
</
beans:beans
>
For
accessing the services:
HelloWorldService
http://localhost:8080/SpringRestService/hello/Naresh/Cherukuri
getProductDetailsService
http://localhost:8080/SpringRestService/getProduct
http://localhost:8080/SpringRestService/getProduct?itemcode=1
Output
JSON:
No comments:
Post a Comment