一、关键步骤

首先,说明一下常用注解的用法:

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

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

RESTful API具体设计如下:

请求类型 URL 功能说明
GET /users 查询用户列表
POST /users 创建一个用户
GET /users/id 根据id查询一个用户
PUT /users/id 根据id更新一个用户
DELETE /users/id 根据id删除一个用户

pom.xml:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <parent>
  5. <groupId>com.wells.demo</groupId>
  6. <artifactId>spring-boot</artifactId>
  7. <version>1.0.0.1</version>
  8. </parent>
  9. <modelVersion>4.0.0</modelVersion>
  10. <artifactId>chapter2-1</artifactId>
  11. <packaging>jar</packaging>
  12. <name>chapter2-1</name>
  13. <description>Demo project for Chapter2-1</description>
  14. <properties>
  15. <java.version>1.8</java.version>
  16. </properties>
  17. <dependencies>
  18. <dependency>
  19. <groupId>org.springframework.boot</groupId>
  20. <artifactId>spring-boot-starter-web</artifactId>
  21. </dependency>
  22. <dependency>
  23. <groupId>org.springframework.boot</groupId>
  24. <artifactId>spring-boot-starter-test</artifactId>
  25. <scope>test</scope>
  26. </dependency>
  27. </dependencies>
  28. <build>
  29. <plugins>
  30. <plugin>
  31. <groupId>org.springframework.boot</groupId>
  32. <artifactId>spring-boot-maven-plugin</artifactId>
  33. </plugin>
  34. </plugins>
  35. </build>
  36. </project>

User实体类定义:

package com.wells.demo.chapter21.entity;


import lombok.Data;

/**
 * Created by Wells on 2019年01月12日
 */

@Data
public class User {
    private Long id;

    private String name;

    private Integer age;
}

UserController实现:

package com.wells.demo.chapter21.controller;

import com.wells.demo.chapter21.entity.User;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Wells on 2019年01月12日
 */

@RestController
@RequestMapping("users")
public class UserController {
    static Map<Long, User> userMap = new HashMap<>();

    @PostMapping("/")
    public String addUser(@ModelAttribute User user){
        userMap.put(user.getId(), user);
        return "success";
    }

    @GetMapping(value = "/{id}")
    public User getUserById(@PathVariable Long id){
        return userMap.get(id);
    }

    @GetMapping("/")
    public List<User> findUserList(){
        List<User> userList = new ArrayList<>();
        for(Map.Entry<Long, User> entry : userMap.entrySet()){
            userList.add(entry.getValue());
        }
        return userList;
    }

    @PutMapping(value = "/{id}")
    public String uptUser(@PathVariable Long id, @ModelAttribute User user){
        User oldUser = userMap.get(id);
        oldUser.setName(user.getName());
        oldUser.setAge(user.getAge());
        userMap.put(id, oldUser);
        return "success";
    }

    @DeleteMapping(value = "/{id}")
    public String delUserById(@PathVariable Long id){
        userMap.remove(id);
        return "success";
    }
}

测试类:

package com.wells.demo.chapter21;

import com.wells.demo.chapter21.controller.UserController;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;

@RunWith(SpringRunner.class)
@SpringBootTest
public class Chapter21ApplicationTests {
    private MockMvc mvc;

    @Before
    public void setup() throws Exception {
        mvc = MockMvcBuilders.standaloneSetup(new UserController()).build();
    }

    @Test
    public void testAddUser() throws Exception{
        // 测试UserController
        RequestBuilder request = null;
        String result = "";

        // 1.post:新增一个user
        request = post("/users/")
                .param("id", "1")
                .param("name", "wells")
                .param("age", "18");
        mvc.perform(request)
                .andExpect(content().string(equalTo("success")));

        // 2.get:根据id查询用户
        request = get("/users/1");
        result = mvc.perform(request)
                .andReturn().getResponse().getContentAsString();
        System.out.println(result);

        // 3.put:修改用户名
        request = put("/users/1")
                .param("age", "20");
        mvc.perform(request)
                .andExpect(content().string(equalTo("success")));

        // 4.get:查询用户列表
        request = get("/users/");
        result = mvc.perform(request)
                .andReturn().getResponse().getContentAsString();
        System.out.println(result);

        // 5.del: 删除用户
        request = delete("/users/1");
        mvc.perform(request)
                .andExpect(content().string(equalTo("success")));

        // 6.get:查询用户列表
        request = get("/users/");
        result = mvc.perform(request)
                .andReturn().getResponse().getContentAsString();
        System.out.println(result);
    }
}

至此,我们通过引入web模块(没有做其他的任何配置),就可以轻松利用Spring MVC的功能,以非常简洁的代码完成了对User对象的RESTful API的创建以及单元测试的编写。

二、代码示例

完整示例:SpringBoot Restful

三、其他说明

RESTful API设计指南:http://www.ruanyifeng.com/blog/2014/05/restful_api.html
MockMVC使用指南:https://blog.csdn.net/Adam_allen/article/details/79919921