一、关键步骤
首先,说明一下常用注解的用法:
- @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:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>com.wells.demo</groupId>
<artifactId>spring-boot</artifactId>
<version>1.0.0.1</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>chapter2-1</artifactId>
<packaging>jar</packaging>
<name>chapter2-1</name>
<description>Demo project for Chapter2-1</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</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