RESTful Web Service example with Spring 4

1. Introduction

We have learnt about the RESTful web service in our previous article. Hope we all have been through that article. If not, I would recommend a quick read by clicking here. In this article, we will create very basic and simple RESTful web service application with Spring MVC. We will primarily concentrate on the RestController in this article, while we go on to create our first RESTful web service application with Spring MVC.

2. Problem Statement

Let’s quickly get into the implementation, and create a simple RESTful API, that extracts the values from the URI (as Path Variables and Request Parameters), and our RestController gets these values to frame the Employee object, which will be finally returned as a JSON response to the client/consumer. Let’s create a RESTful operation URI something like –

http://localhost:8080/RESTWithSpringMVC/API/Employee/{EmployeeName}/{EmailAddress}?id={EmployeeId}


In the above URI, EmployeeName and EmailAddress are the Path Variables, whereas id is the Request Param.

3. Implementation

To start with the implementation, let’s first configure the POM dependencies –

pom.xml

Make sure that we have the dependencies properly configured.

Next is to configure web.xml file for our application –

web.xml

Note the highlighted section in the above code. We have specified the dispatcher servlet <url-pattern> as ‘/API/*’, since we want the RESTful operation URI to be exactly as per the problem statement. (Check out the plum colored text in the RESTful operation URI we have specified under the Problem Statement section above.)

Now let’s create the mvc-dispatcher-servlet.xml as our web application context

mvc-dispatcher-servlet.xml

As we will be dealing with the employees in this example, let’s create the entity class for Employee –

Employee.java

Now the important component, i.e. the REST Controller.

EmployeeController.java

Following points can be noted in the above EmployeeController class that we have created –

  1. Spring 4 has introduced the @RestController annotation, which is equivalent to the combination of @Controller and the @ResponseBody in Spring 3.
  2. We have specified @RequestMapping annotation at the class level for the URI pattern ‘/Employee’. Tomorrow we expect a possibility to deal with Students instead of Employees. In that case, we would need to create the StudentController additionaly, that would be applicable for all the URI patterns with ‘/Students’.
  3. There are other @RequestMapping annotations at the method level, whose value must be different for different methods. However, all the methods that we map would be applicable for the requests with ‘/Employee’ as the base URL pattern.
  4. @RequestMapping with value = “/{name}/{emailId:.+}” is to map the Path Variables for employee name and employee’s emailId. This means the request URI – http://localhost:8080/RESTWithSpringMVC/API/Employee/abhimanyu/abc@gmail.com?id=1234, will map ‘abhimanyu’ with the {name} field and ‘abc@gmail.com’ to the {emailId:.+} field in the RequestMapping as the Path variables.
  5. @PathVariable(“name”) String name will extract the {name} as Path Variable into a String object.
  6. @RequestParam(value = “id”, required = false, defaultValue = “00000”) final String id will map the URI request parameter named ‘id‘ into a String object. Note that this request param is optional, which if unavailable, will hold the default value as ‘00000’.
  7. We are explicitly handling HTTP GET requests only.
  8. The Employee object that is returned, is parsed and processed into the respective JSON format by the @RestController, which internally invokes the Jackson API to get this done.

4. Running the Application

We are almost done. Let’s check out. Build the application, add and publish it to the server. Now hit the following RESTful operation URI –

http://localhost:8080/RESTWithSpringMVC/API/Employee/abhimanyu/abc@gmail.com?empId=1234

Yes, you might probably encounter an error, something like –

Restful Web Service Error

5. Solving the error

As expected, the above issue arises because of the emailId being one of the Path Variables. I deliberately took this scenario to our demo application, so you are well aware of how to deal with this.

Basically, when the email id is passed in the URL, Spring detects the ‘.’ (dot) character in it and uses it to determine the requested media type. So when the request URI is hit with Path Variable as abc@gmail.com, Spring takes in as we are requesting for a .com type of data, which is definitely not acceptable according to the standard request “accept” headers that are used. Hence, we see the error in the above snapshot. Had we used abc@gmail.json instead, Spring would have gracefully accepted our request for a JSON data, and there would have been no errors and the output would have been –

Restful Web Service Example

Still we haven’t yet arrived at the solution. I don’t want the user emails to be displayed with .json extension instead of .com.

So to solve this issue, we just need to slightly modify our mvc-dispatcher-servlet.xml to –

Note that in the above highlighted section in the code, we have modified the default favorPathExtension property value to false, which will no longer try to determine the requested media type from any of the Path Variables in the HTTP Request URI.

Now when we run the application, we can see the proper JSON response being generated as –

Restful Web Service Application - Success Response

Also worth reading – RESTful Web Service example with XML response

4. Download source code

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.