Spring MVC RESTFul Web Service CRUD Example

This tutorial shows you how to build a Spring MVC RESTFul Web Service CRUD Example. In this example, we create a rest controller with CRUD operations like Create, Read, Update and Delete. This rest service consumes and produces JSON.

Table of contents:
1. Project structure
2. Maven Dependencies
3. Create Rest Controller
4. Configure the Dispatcher Servlet
5. Spring MVC Configuration
6. Controller Endpoint
7. Create the Fruit Service
8. Create dummy Data Access Object (DAO)
9. Deploy Spring MVC RESTFul Web Service CRUD Example

Other interesting posts you may like

Now, let us to create the Spring MVC RESTFul Web Service CRUD Example step by step

Project structure
The project structure should be such as below

Spring MVC RESTFul Web Service CRUD Example project

Maven Dependencies

We need to use the following dependencies that supports to return object with JSON structure

Notices: By setting the failOnMissingWebXml to false we tell the compiler not to fail on a missing web.xml file.

Create Rest Controller
Now, let us create the Rest Controller by implementing Rest API. This is what our Rest Controller exposes:

GET incoming request to /fruits returns a list of fruits
GET incoming request to /fruits/1 returns the fruit with id 1
POST incoming request to /fruits with a fruit object in JSON creates a new fruit
PUT incoming request to /fruits/4 with a fruit object in JSON updates the fruit with id 4
DELETE incoming request to /fruits/1 deletes the fruit with id 1

@RestController is a convenience annotation that does nothing more than adding the @Controller and @ResponseBody annotations.
@RequestMapping annotation for mapping web requests onto specific handler classes and/or handler methods. Provides a consistent style between Servlet and Portlet environments, with the semantics adapting to the concrete environment. A class-level annotation like /users maps a specific request path onto a controller. Method-level annotations narrow the mapping for a specific HTTP request method like GET, PUT, POST or DELETE.

@PathVariable annotation which indicates that a method parameter should be bound to a URI template variable.
The URI Template “/fruits/{id}” specifies the variable name id. When the controller handles this request, the value of id is set to the value found in the appropriate part of the URI. For example, when a request comes in for /fruits/1, the value of id is 1.

@RequestBody annotation indicating a method parameter should be bound to the body of the web request. The body of the request is passed through an HttpMessageConverter to resolve the method argument depending on the content type of the request. Optionally, automatic validation can be applied by annotating the argument with @Valid.

@ResponseBody annotation that indicates a method return value should be bound to the web response body. By annotating the class with @RestController, no longer need to add this annotation to every method individually

ResponseEntity extends from HttpEntity that adds a HttpStatus status code to the response.

HttpHeaders represents HTTP request and response headers, mapping string header names to a list of string values.

CorsFilter
Cross Origin Resource Sharing or CORS is a common issue of the application that uses AJAX. Most browsers block requests from another domain outside the origin domain for security reasons. To fix this issue in Spring MVC 4 we will create a filter to set the Access-Control-Allow-Origin header in the response to accept all clients or only permitted clients access the resources on the other domain. We have the completely tutorial about Cross Origin Resource Sharing so we will don’t discuss here. Please refer to the post Cross Origin Request Blocked Spring MVC Restful Angularjs.

Configure the Dispatcher Servlet
The DispatcherServlet is used to dispatch the requests to the appropriate controller methods. We configure it by extending the AbstractAnnotationConfigDispatcherServletInitializer. Then we register the Spring MVC java Configuration file (Here is MyWebMvcConfig class) with DispatcherServlet in the getServletConfigClasses method and other filter.

Spring MVC Configuration
The @Configuration annotation indicates that the class can be used by the Spring IoC container as a source of bean definitions.

The @EnableWebMvc is equivalent to in XML. The @EnableWebMvc enables support for the @Controller annotation that uses @RequestMapping to map incomming requests to certain methods.

The @ComponentScan will instruct spring which packages it may scan to discover spring annotated beans.

Controller Endpoint
The Fruit POJO will be acts as a model

Create the Fruit Service

and implementation class

Create dummy Data Access Object (DAO)
Here, we are creating the dummy Fruit DAO for this example

and implementation class

Deploy Spring MVC RESTFul Web Service CRUD Example
After building the project by maven we deploy the file war on application server (Tomcat 8 for example). Now, it’s time to test this service. We are using the plugin DHC REST Client on Chrome to call all the below APIs.

1. Getting all the fruits

The GET incoming request http://localhost:8080/restful-crud-example/fruits returns a list of fruits in JSON format.

Spring MVC RESTFul Web Service CRUD Example getall

2. Getting a fruit by id

The GET incoming request http://localhost:8080/restful-crud-example/fruits/1 returns a fruits in JSON format.

Spring MVC RESTFul Web Service CRUD Example get Id

3. Creating a new Fruit

The POST incoming request http://localhost:8080/restful-crud-example/fruits
This request is sending JSON format so we need to add a Content-Type header with the value application/json.

Spring MVC RESTFul Web Service CRUD Example created

We do the step 1 again, we can see that a new fruit has been added.

Restful-CRUD-Example-getall-again

4. Updating a Fruit

The PUT incoming request http://localhost:8080/restful-crud-example/fruits/4

Spring MVC RESTFul Web Service CRUD Example update

5. Deleting a Fruit

The DELETE incoming request http://localhost:8081/spring-mvc-rest/users/1

Spring MVC RESTFul Web Service CRUD Example delete

That’s all on how to build Spring MVC RESTFul Web Service CRUD Example.

Download complete source code of example, please click link below

Spring-MVC-4-Restful-Web-Service-CRUD-Example.zip (221 downloads)

Leave a Comment

*

Please share it if you found this useful
Hide Buttons