Sunday, September 21, 2014

Rest web services using Spring

Restful services are the most popular way of handling way services currently. And the favourite way of doing data exchange is JSON and not XML as JSON is quite compact and size of payload is quite less. Restful web services work over HTTP protocol and is literally about reading and wring JSON data structure. Spring support restful web services using the controller mechanism. Let's look into an example of Rest based web services using Spring 4.0.5.RELEASE version.

If you are using Spring mvc then a lot of infrastructure would have been already wired. However let's
look into the steps to see how the things will work. Here we will cover only the pieces that are relevant to hook web services. For a full fledged web application which includes rest based web services follow this post.

Register the Dispatcher servlet

Register the dispatcher servlet in web.xml and configure it to trap the rest based calls

<!-- Spring servlet that will handle the requests -->

<!-- If you have mvc enabled, you will be including the url-pattern for front end also here -->

Configure the Spring context

The next step is to configure the Spring context, which is this case would be mvc.xml sitting in WEB-INF/spring directory. Adjust your path accordingly in web.xml. A sample mvc.xml would look like

<!-- Tells Spring to scan for mvc based annotations -->

<!-- packages to scan for annotation -->
<context:component-scan base-package=
          "" />

In this case our web services class would be sitting in the package as mentioned in base-package value.

Web service class

Let's write the actual web service class now.

// Note the RestController annotation. 
// This tells Spring that it is a rest based web service
public class UsersRestController {

    //Inject the service class which will do the heavy lifting
  @Resource UserService userService;
// Here the actual fun happens
// The web service signature is specified by value
// method tell if GET or POST or both will be honoured
    @RequestMapping(value = "/rest/users", 
                        method = RequestMethod.GET)
    public @ResponseBody List<User> getUserList() {
        List<User> usersList= userService.getListOfUsers();
        return usersList;


Web service Invocation

This particular web service can be invoked using the following url:

http(s)://<server>/<application context>/ws/rest/users

ws is used by container to map to Dispatcher servlet and /rest/users is mapped to the defined method by Spring. This will return a json response back to the client. 

No comments:

Post a Comment