Monday, May 4, 2015

Spring RESTful web service simple example

In this quick and simple example you will learn how to write a RESTful web service with Spring in five minutes.
First create a new maven project. Below are my configurations.
Group Id: com.example
Artifact Id: SpringRestExample
Packaging: war

Add required dependencies to pom.xml. My pom.xml is now looks like this.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>prageeth.example</groupId>
  <artifactId>SpringRestExample</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <dependencies>
 <dependency>
  <scope>provided</scope>
  <groupId>javax.servlet</groupId>
  <artifactId>servlet-api</artifactId>
  <version>2.5</version>

 </dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-webmvc</artifactId>
<version>2.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.0.7.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.0.7.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.0.7.RELEASE</version>
</dependency>
  </dependencies>
</project>

Create web.xml file in main/webapp/WEB-INF folder and add entry for DispatcherServlet.
My web.xml is as below.
<web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee   
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemalocation="http://java.sun.com/xml/ns/j2ee 
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <servlet>
<servlet-name>mySpringRest</servlet-name>
<servlet-class> 
           org.springframework.web.servlet.DispatcherServlet      
        </servlet-class>
<load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
<servlet-name>mySpringRest</servlet-name>
<url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

You can see I have defined the DispatcherServlet as mySpringRest in web.xml file.
So I have to create the file mySpringRest-servlet.xml in WEB-INF folder.

Now create the class RestExample in package com.example. This is the class in which we are going to write our RESTful services. I add one service method in to this class.

package com.example;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class RestExample {
  
  @RequestMapping(value="/hello", method = RequestMethod.GET)
  public String sayHello() {
    return "Hello!";
  }
}

Since I am using Spring annotations and my annotated classes are in com.example package, in my mySpringRest-servlet.xml file I say spirng to scan that package for annotated classes.

This is my final mySpringRest-servlet.xml file.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

<context:component-scan base-package="com.example" />
<mvc:annotation-driven />

</beans>

Now run the project and test the url http://localhost:8080/SpringRestExample/user/hello
You will receive the message "hello".

You can write your service method to accept request parameters as below.
package com.example;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class RestExample {

  @RequestMapping(value = "/hello", method = RequestMethod.GET)
  public String sayHello(@RequestParam(required=false, defaultValue="") String name) {
    return "Hello " + name + "!";
  }
}
Call the service like this to see the result.
http://localhost:8080/SpringRestExample/user/hello?name=john

You can write your service method to access path variables(path parameters) as below.
package com.example;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class RestExample {
  
  @RequestMapping("/{regNumber}/{name}")
  public String sayHello(@PathVariable Integer regNumber, @PathVariable String name) {
    return "Hello " + name + ".Your registration number is " + regNumber;
  }
}

Call the service as below to see the output.
http://localhost:8080/SpringRestExample/user/123/john