Creating a Spring MVC REST WebService

To get started let’s create a simple dynamic web project in Eclipse.

1. Modify web.xml to let it know about Spring

 <servlet-name>springapp</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>springapp</servlet-name>
<url-pattern>/service/*</url-pattern>
</servlet-mapping>

Additional Step: Add Spring Jars or Maven dependencies for Spring- core, aop, context, web and webmvc jars.

2. create springapp-servlet.xml

<?xml version=”1.0″ encoding=”UTF-8″?>

<beans xmlns=”http://www.springframework.org/schema/beans”
xmlns:mvc=”http://www.springframework.org/schema/mvc” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xmlns:p=”http://www.springframework.org/schema/p” xmlns:context=”http://www.springframework.org/schema/context”
xsi:schemaLocation=”http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd”
>
<!– the application context definition for the springapp DispatcherServlet –>

<mvc:annotation-driven />
<context:annotation-config />

<context:component-scan base-package=”com.kamal.test” />

<!–   <bean name=”/hello.app” class=”com.kamal.test.Hello”/> –>

</beans>

Note that we are using annotation driven implementation. where our package com.kamal.test would be scanned for any available components.

3. Create the service

package com.kamal.test;

import java.io.IOException;
import javax.servlet.ServletException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(“/sample”)
public class SampleService {
@RequestMapping(method = RequestMethod.GET, value=”/details/{id}”)

public @ResponseBody String LepService(@PathVariable(“id”) String id )
throws ServletException, IOException {
String success=”Sucess”;
//Do something here
return success;
}
}