Spring restful web services example step by step

In this tutorial, we are going to create Spring restful web services step by step.

We will create a simple Spring restful web services which will return JSON as a response.

Here is project structure for the application.

Project structure

Step 1: Create a dynamic web project using maven in eclipse.

Maven configuration

Step 2: Add require dependencies to pom.xml.

Please note that we have put “jackson-databind” as dependency here, so spring will load Jackson2JsonMessageConverter into the classpath,so whenever we have any requst with “application/json”,Jackson2JsonMessageConverter will take care of required conversions.

Web configuration

Step 3: Change web.xml as below:

Step 4: create a xml file called springrestweb-servlet.xml in /WEB-INF/ folder.Please note that file name should be “$servlent-name” with “-servlet” as prefix.
Please change context:component-scan if you want to use different package for spring to search for controller.

Create model

Step 5: Create model class Customer.java as below.

Create controller

Step 6: Create controller class named CustomerController.java as below.

@RequestMapping annotation is used to map web requests to controller method.
For example:
If we have request as “http://localhost:8080/SpringRestfulWebServicesExample/customers” then getCustomers will be called from above controller.
Please note that we have used @RestConstroller to get resource as response.We don’t need to specify @ResponseBody any more.
In spring 4.0, we can use @RestController which is combination of @Controller + @ResponseBody.

Build maven project

Step 7: Build your maven project.
Right click on project -> Run as -> Maven build
maven build
Step 8: Put “clean install” as maven goals.
maven clean install
click on run.

Run the application

Step 9:Run the application.
Right click on project -> run as -> run on server
run on server

Select apache tomcat and click on finish

Browser REST URLs

Step 10: Browse below URL
URL: “http://localhost:8080/SpringRestfulWebServicesExample/customers”
get all customers
Now let’s get customer by id.
URL: “http://localhost:8080/SpringRestfulWebServicesExample/customer/3”
get customer by id

Source code

Source code url for spring restful web services example step by step

That’s all about spring restful web services example step by step.

Leave a Reply

Your email address will not be published. Required fields are marked *