构建RESTful API(十八)

首先,回顾并详细说明一下在快速入门中使用的@Controller@RestController@RequestMapping注解。如果您对Spring MVC不熟悉并且还没有尝试过快速入门案例,建议先看一下快速入门的内容。

  • @Controller:修饰class,用来创建处理http请求的对象
  • @RestController:Spring4之后加入的注解,原来在@Controller中返回json需要@ResponseBody来配合,如果直接用@RestController替代@Controller就不需要再配置@ResponseBody,默认返回json格式。
  • @RequestMapping:配置url映射

下面我们尝试使用Spring MVC来实现一组对User对象操作的RESTful API,配合注释详细说明在Spring MVC中如何映射HTTP请求、如何传参、如何编写单元测试。

RESTful API具体设计如下:

User实体定义:

1
2
3
4
5
6
7
8
9
public  class  User {
  
     private  Long id;
     private  String name;
     private  Integer age;
  
     // 省略setter和getter
      
}

  

实现对User对象的操作接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
@RestController
@RequestMapping (value= "/users" )      // 通过这里配置使下面的映射都在/users下
public  class  UserController {
  
     // 创建线程安全的Map
     static  Map<Long, User> users = Collections.synchronizedMap( new  HashMap<Long, User>());
  
     @RequestMapping (value= "/" , method=RequestMethod.GET)
     public  List<User> getUserList() {
         // 处理"/users/"的GET请求,用来获取用户列表
         // 还可以通过@RequestParam从页面中传递参数来进行查询条件或者翻页信息的传递
         List<User> r =  new  ArrayList<User>(users.values());
         return  r;
     }
  
     @RequestMapping (value= "/" , method=RequestMethod.POST)
     public  String postUser( @ModelAttribute  User user) {
         // 处理"/users/"的POST请求,用来创建User
         // 除了@ModelAttribute绑定参数之外,还可以通过@RequestParam从页面中传递参数
         users.put(user.getId(), user);
         return  "success" ;
     }
  
     @RequestMapping (value= "/{id}" , method=RequestMethod.GET)
     public  User getUser( @PathVariable  Long id) {
         // 处理"/users/{id}"的GET请求,用来获取url中id值的User信息
         // url中的id可通过@PathVariable绑定到函数的参数中
         return  users.get(id);
     }
  
     @RequestMapping (value= "/{id}" , method=RequestMethod.PUT)
     public  String putUser( @PathVariable  Long id,  @ModelAttribute  User user) {
         // 处理"/users/{id}"的PUT请求,用来更新User信息
         User u = users.get(id);
         u.setName(user.getName());
         u.setAge(user.getAge());
         users.put(id, u);
         return  "success" ;
     }
  
     @RequestMapping (value= "/{id}" , method=RequestMethod.DELETE)
     public  String deleteUser( @PathVariable  Long id) {
         // 处理"/users/{id}"的DELETE请求,用来删除User
         users.remove(id);
         return  "success" ;
     }
  
}

  

猜你喜欢

转载自www.cnblogs.com/MaxElephant/p/10232083.html