在Spring 3中,对旧的RequestMapping
类进行了增强以支持RESTful功能,这使Spring开发人员可以更轻松地在Spring MVC中开发REST服务。
在本教程中,我们向您展示如何使用Spring 3 MVC注释来开发RESTful风格的Web应用程序。
1.项目目录
查看项目文件夹结构。
2.项目依赖性
要在Spring MVC中开发REST,只需包含核心Spring和Spring MVC依赖项即可。
pom.xml
<properties>
<spring.version>3.0.5.RELEASE</spring.version>
</properties>
<dependencies>
<!-- Spring 3 dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
</project>
3. REST控制器
对于Spring RESTful,您需要PathVariable
, RequestMapping
和RequestMethod
。 以下代码应该是不言自明的。
MovieController.java
package com.mkyong.common.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("/movie")
public class MovieController {
@RequestMapping(value = "/{name}", method = RequestMethod.GET)
public String getMovie(@PathVariable String name, ModelMap model) {
model.addAttribute("movie", name);
return "list";
}
@RequestMapping(value = "/", method = RequestMethod.GET)
public String getDefaultMovie(ModelMap model) {
model.addAttribute("movie", "this is default movie");
return "list";
}
}
4. JSP视图
一个显示该值的JSP页面。
list.jsp
<html>
<body>
<h1>Spring 3 MVC REST web service</h1>
<h2>Movie Name : ${movie}</h2>
</body>
</html>
5.演示
请参阅REST URL演示。
网址: http:// localhost:8080 / SpringMVC / movie / ironMan
网址: http:// localhost:8080 / SpringMVC / movie / SpiderMan4
下载源代码
下载它– Spring3MVC-REST-HelloWorld-Example.zip (7 KB)
参考文献
- http://en.wikipedia.org/wiki/Representational_State_Transfer
- http://blog.springsource.com/2009/03/08/rest-in-spring-3-mvc/
翻译自: https://mkyong.com/spring-mvc/spring-3-rest-hello-world-example/