Spring MVC RESTFul Web Service CRUD 例子

本文主要翻译自:http://memorynotfound.com/spring-mvc-restful-web-service-crud-example/

本文主要讲解如何使用Spring MVC4搭建RestFul Web service。我们新建一个进行CRUD操作的controller,使用http方法的POST、GET、PUT、DELETE来区分新建、查询、修改、删除。这个rest service使用json进行数据传输。我们使用CrossOrigin来解决跨域问题。

Rest Controller

使用spring MVC4实现 一个REST Web Service 有很多种方式,我们选取下面这种最简单的。使用ResponseEntity直接控制response的响应头和http状态码。

  • http GET方法 /users 请求全部用户数据
  • http GET方法 /users/1 请求id为1的用户
  • http POST方法 /users 使用json格式新建一个用户
  • http PUT方法 /users/1 修改id为1的用户
  • http DELETE方法 /users/1 删除id为1的用户
  1. package com.memorynotfound.controller;
  2. import com.memorynotfound.model.User;
  3. import com.memorynotfound.service.UserService;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.http.HttpHeaders;
  8. import org.springframework.http.HttpStatus;
  9. import org.springframework.http.ResponseEntity;
  10. import org.springframework.web.bind.annotation.*;
  11. import org.springframework.web.util.UriComponentsBuilder;
  12. import java.util.List;
  13. @RestController
  14. @RequestMapping("/users")
  15. public class UserController {
  16. private final Logger LOG = LoggerFactory.getLogger(UserController.class);
  17. @Autowired
  18. private UserService userService;
  19. // =========================================== Get All Users ==========================================
  20. @RequestMapping(method = RequestMethod.GET)
  21. public ResponseEntity<List<User>> getAll() {
  22. LOG.info("getting all users");
  23. List<User> users = userService.getAll();
  24. if (users == null || users.isEmpty()){
  25. LOG.info("no users found");
  26. return new ResponseEntity<List<User>>(HttpStatus.NO_CONTENT);
  27. }
  28. return new ResponseEntity<List<User>>(users, HttpStatus.OK);
  29. }
  30. // =========================================== Get User By ID =========================================
  31. @RequestMapping(value = "{id}", method = RequestMethod.GET)
  32. public ResponseEntity<User> get(@PathVariable("id") int id){
  33. LOG.info("getting user with id: {}", id);
  34. User user = userService.findById(id);
  35. if (user == null){
  36. LOG.info("user with id {} not found", id);
  37. return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
  38. }
  39. return new ResponseEntity<User>(user, HttpStatus.OK);
  40. }
  41. // =========================================== Create New User ========================================
  42. @RequestMapping(method = RequestMethod.POST)
  43. public ResponseEntity<Void> create(@RequestBody User user, UriComponentsBuilder ucBuilder){
  44. LOG.info("creating new user: {}", user);
  45. if (userService.exists(user)){
  46. LOG.info("a user with name " + user.getUsername() + " already exists");
  47. return new ResponseEntity<Void>(HttpStatus.CONFLICT);
  48. }
  49. userService.create(user);
  50. HttpHeaders headers = new HttpHeaders();
  51. headers.setLocation(ucBuilder.path("/user/{id}").buildAndExpand(user.getId()).toUri());
  52. return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
  53. }
  54. // =========================================== Update Existing User ===================================
  55. @RequestMapping(value = "{id}", method = RequestMethod.PUT)
  56. public ResponseEntity<User> update(@PathVariable int id, @RequestBody User user){
  57. LOG.info("updating user: {}", user);
  58. User currentUser = userService.findById(id);
  59. if (currentUser == null){
  60. LOG.info("User with id {} not found", id);
  61. return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
  62. }
  63. currentUser.setId(user.getId());
  64. currentUser.setUsername(user.getUsername());
  65. userService.update(user);
  66. return new ResponseEntity<User>(currentUser, HttpStatus.OK);
  67. }
  68. // =========================================== Delete User ============================================
  69. @RequestMapping(value = "{id}", method = RequestMethod.DELETE)
  70. public ResponseEntity<Void> delete(@PathVariable("id") int id){
  71. LOG.info("deleting user with id: {}", id);
  72. User user = userService.findById(id);
  73. if (user == null){
  74. LOG.info("Unable to delete. User with id {} not found", id);
  75. return new ResponseEntity<Void>(HttpStatus.NOT_FOUND);
  76. }
  77. userService.delete(id);
  78. return new ResponseEntity<Void>(HttpStatus.OK);
  79. }
  80. }
  • @RestController 只是@Controller 和@ResponseBody的简化使用。就是使用了@RequestController后不再需要在每个方法上设置@ResponseBody。
  • @RequestMapping 是个老朋友了,就是url到控制器的映射关系定义,这边主要是使用url+http方法进行定义。一般在类上定义根url,如/users,然后在每个方法上在此基础上定义。
  • @PathVariable 方法参数从uri中提取。Spring MVC需要从URI模板中通过name查找参数值,然后注入到方法中。
  • @RequestBody 暗示方法参数绑定到请求体中的数据。一个HttpMessageConverter会负责将请求体中的json数据转化并装配到参数中。
  • @ResponseBody 暗示返回的数据直接写入到Response body中。就像上面说的,使用了@RestController后不再需要设置。
  • ResponseEntity 作为HttpEntity的子类,可以设置HttpStatus 状态码。ResponseEntity代码整个HTTP响应,可以添加响应头,状态码,并设置Response body。
  • HttpHeaders 表示 HTTP 的 请求头和响应头。这个类可以方便地设置Content-Type和Access-Content-Allow-Headers等。

CorsFilter

跨域问题直接使用Spring MVC提供的CorsFilter可以简单解决或者在xml中设置mvc:cors

  1. <filter>
  2. <filter-name>cors</filter-name>
  3. <filter-class>org.springframework.web.filter.CorsFilter</filter-class>
  4. </filter>
  5. <filter-mapping>
  6. <filter-name>cors</filter-name>
  7. <url-pattern>/*</url-pattern>
  8. </filter-mapping>

具体可以查看: spring MVC cors跨域实现源码解析

maven依赖


  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  5. http://maven.apache.org/xsd/maven-4.0.0.xsd">
  6. <modelVersion>4.0.0</modelVersion>
  7. <groupId>com.memorynotfound.spring.mvc.rest</groupId>
  8. <artifactId>crud</artifactId>
  9. <version>1.0.0-SNAPSHOT</version>
  10. <name>SPRING-MVC - ${project.artifactId}</name>
  11. <url>http://memorynotfound.com</url>
  12. <packaging>war</packaging>
  13. <properties>
  14. <spring.version>4.2.6.RELEASE</spring.version>
  15. <jackson.version>2.7.4</jackson.version>
  16. <logback.version>1.1.7</logback.version>
  17. </properties>
  18. <dependencies>
  19. <!-- spring libraries -->
  20. <dependency>
  21. <groupId>org.springframework</groupId>
  22. <artifactId>spring-webmvc</artifactId>
  23. <version>${spring.version}</version>
  24. </dependency>
  25. <!-- Needed for JSON View -->
  26. <dependency>
  27. <groupId>com.fasterxml.jackson.core</groupId>
  28. <artifactId>jackson-databind</artifactId>
  29. <version>${jackson.version}</version>
  30. </dependency>
  31. <!-- logging -->
  32. <dependency>
  33. <groupId>ch.qos.logback</groupId>
  34. <artifactId>logback-classic</artifactId>
  35. <version>${logback.version}</version>
  36. </dependency>
  37. <!-- servlet api -->
  38. <dependency>
  39. <groupId>javax.servlet</groupId>
  40. <artifactId>javax.servlet-api</artifactId>
  41. <version>3.1.0</version>
  42. <scope>provided</scope>
  43. </dependency>
  44. </dependencies>
  45. <build>
  46. <plugins>
  47. <plugin>
  48. <groupId>org.apache.maven.plugins</groupId>
  49. <artifactId>maven-compiler-plugin</artifactId>
  50. <version>3.2</version>
  51. <configuration>
  52. <source>1.7</source>
  53. <target>1.7</target>
  54. </configuration>
  55. </plugin>
  56. <plugin>
  57. <artifactId>maven-war-plugin</artifactId>
  58. <version>2.6</version>
  59. <configuration>
  60. <failOnMissingWebXml>false</failOnMissingWebXml>
  61. </configuration>
  62. </plugin>
  63. </plugins>
  64. </build>
  65. </project>

[翻译]Spring MVC RESTFul Web Service CRUD 例子的更多相关文章

  1. 构建一个基于 Spring 的 RESTful Web Service

    本文详细介绍了基于Spring创建一个“hello world” RESTful web service工程的步骤. 目标 构建一个service,接收如下HTTP GET请求: http://loc ...

  2. 【转】Building a RESTful Web Service

    目标 构建一个service,接收如下HTTP GET请求: [plain] view plain copy   http://localhost:8080/greeting 并返回如下JSON格式的 ...

  3. 【转】基于CXF Java 搭建Web Service (Restful Web Service与基于SOAP的Web Service混合方案)

    转载:http://www.cnblogs.com/windwithlife/archive/2013/03/03/2942157.html 一,选择一个合适的,Web开发环境: 我选择的是Eclip ...

  4. 用Spring Tools Suite(STS)开始一个RESTful Web Service

    spring.io官方提供的例子Building a RESTful Web Service提供了用Maven.Gradle.STS构建一个RESTFul Web Service,实际上采用STS构建 ...

  5. Building a RESTful Web Service Using Spring Boot In Eclipse

    一.构建restful web service 创建Maven的java web工程,maven的pom文件加入依赖包 创建包hello Greeting.java package hello; pu ...

  6. Apache CXF实现Web Service(4)——Tomcat容器和Spring实现JAX-RS(RESTful) web service

    准备 我们仍然使用 Apache CXF实现Web Service(2)——不借助重量级Web容器和Spring实现一个纯的JAX-RS(RESTful) web service 中的代码作为基础,并 ...

  7. Apache CXF实现Web Service(3)——Tomcat容器和不借助Spring的普通Servlet实现JAX-RS(RESTful) web service

    起步 参照这一系列的另外一篇文章: Apache CXF实现Web Service(2)——不借助重量级Web容器和Spring实现一个纯的JAX-RS(RESTful) web service 首先 ...

  8. 【转】Spring 4.x实现Restful web service

    http://my.oschina.net/yuyidi/blog/352909 首先我们还是跟之前一样,创建一个maven项目,不过因为Spring Restful web service是基于Sp ...

  9. 在GlassFish应用服务器上创建并运行你的第一个Restful Web Service【翻译】

    前言 本人一直开发Android应用,目前Android就业形势恶劣,甚至会一路下滑,因此决定学习服务器开发.采用的语言是java,IDE是Intellij,在下载Intellij的同时看到官网很多优 ...

随机推荐

  1. body{font-size: 62.5%;} 解释

    为什么body{font-size: 62.5%;} 2012-10-25 16:15 16778人阅读 评论(0) 收藏 举报  分类: css问题(17)  在网页设计中我们经常看见body{fo ...

  2. 根据PID寻找程序源位置--lsof

    ulimit其实就是对单一程序的限制,进程级别的 file-max是所有时程最大的文件数 nr_open是单个进程可分配的最大文件数 确认系统设置的最大文件句柄数 ulimit -a 统计系统中当前打 ...

  3. Haskell语言学习笔记(35)Contravariant

    contravariant 模块 contravariant 模块需要安装 $ cabal install contravariant contravariant-1.4 Prelude> :m ...

  4. Delphi 解析系统环境变量

    // http://www.outofmemory.cn function ExpandEnvironment(const strValue: string): string; var chrResu ...

  5. 注册驱动MySQL的驱动程序

    1.将驱动程序文件添加到应用项目 将驱动程序mysql-connector-Java-5.1.6-bin,复制到web应用程序的web-INF\lib下,web应用程序就可以通过JDBC接口访问MyS ...

  6. C#累加器函数Aggregate用法 讲解

    Enumerable.Aggregate 扩展方法在System.Linq命名空间中,是Enumerable类的第一个方法(按字母顺序排名),但确是Enumerable里面相对复杂的方法. MSDN对 ...

  7. docker问题

    Docker报错 WARNING: IPv4 forwarding is disabled. Networking will not work. 解决办法: # vim /usr/lib/sysctl ...

  8. 关于number...的精度问题

    一 当数字的精度被定为number(3,2)时, 这时他能输入的数字整数部分只能是3-2=1位, 小数位如果不够会用0补齐, 超出的四舍五入保留3位小数. SQL> insert into t_ ...

  9. 'org.springframework.beans.factory.xml.XmlBeanFactory' is deprecated

    'org.springframework.beans.factory.xml.XmlBeanFactory' is deprecated XmlBeanFactory这个类已经被摒弃了.可以用以下代替 ...

  10. 在MyEclipse Tomcat可以运行但是在Tomcat 6.x上却不可以运行