Spring Restful web services example

In this post, we will see Spring Restful web services example.

We have already seen Restful web services tutorial and Spring mvc web example. In this post, we will see combination of both.

Spring have started supporting Restful web services after Spring 3 version. In this post, we will see how to create Restful web services with Spring framework.If you want complete integration with hibernate and mysql, you can go through Spring Restful hibernate mysql example.

Here are steps to create a simple Spring Restful web services which will return plain text.

1) Create a dynamic web project using maven in eclipse.
2) Now change pom.xml as follows:
pom.xml

Spring application configuration:

3) Change web.xml as below:

4) create a xml file named springrest-servlet.xml in /WEB-INF/ folder.
Please change context:component-scan if you want to use different package for spring to search for controller.Please refer to spring mvc hello world example for more understanding.

Create controller

5) Create a controller named “SpringRestController.java”

@PathVariable: Used to inject values from the URL into a method parameter.This way you inject name in hello method .

We are not providing any view information in springrest-servlet.xml as we do in Spring MVC. If we need to directly get resource from controller, we need to return @ResponseBody as per Spring 3 but with Spring 4, we can use @RestController for that.
In spring 4.0, we can use @RestController which is combination of @Controller + @ResponseBody.

6) It ‘s time to do maven build.

Right click on project -> Run as -> Maven build
7) Provide goals as clean install (given below) and click on run

Run the application

8) Right click on project -> run as -> run on server
Select apache tomcat and click on finish
9) Test your REST service under: “http://localhost:8080/SpringRestfulWebServicesExample/hello/arpit”.
You will get following output:

Download

click to begin
20KB .zip
We are done with Spring Restful web services example. If you are still facing any issue, please comment.

3 Comments

  1. Devesh A September 30, 2015
  2. Thirukumaran January 4, 2016
    • Ankit joshi January 9, 2017

Add Comment