This tutorial provides a simple example for writing the Spring MVC REST services using the Spring 4 APIs. We have written several articles about the spring 4 features in our previous articles. The REST implementation on Spriing 4 also very much similiar to the previous releases. Here I have provided the sample source code what I have used to implement the REST services. If you have any questions, please write it in the comments section.
Also Read:
SpringMVC4HelloWorld.java
package javabeat.net.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller @RequestMapping("/springmvc4") public class SpringMVC4HelloWorld { @RequestMapping(value = "/hello", method = RequestMethod.GET) public String hello(ModelMap model) { model.addAttribute("msg", "JavaBeat Hello World!"); return "helloWorld"; } @RequestMapping(value = "/greetings/{msg}", method = RequestMethod.GET) public String greetingsMsg(@PathVariable String msg, ModelMap model) { model.addAttribute("msg", msg); return "helloWorld"; } }
helloWorld.jsp
<html> <body> <h1>Spring MVC 4.0 REST Example</h1> <h3>Your Message : ${msg}</h3> </body> </html>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>Spring MVC 4.0 Web Application</display-name> <servlet> <servlet-name>spring4-mvc-dispatcher</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring4-mvc-dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
spring4-mvc-dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <context:component-scan base-package="javabeat.net.controller" /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/jsp/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> </beans>