【Spring Security OAuth2笔记系列】- 【使用Spring MVC开发RESTful API】 编写用户详情服务

编写用户详情服务

本节内容

  • @PathVariable映射url片段到java方法的参数
  • 在url声明中使用正则表达式
  • @JsonView控制json输出内容

编写测试用例

    // 获取用户详情成功测试用例
    @Test
    public void whenGetInfoSuccess() throws Exception {
        mockMvc.perform(get("/user/1")
                .contentType(MediaType.APPLICATION_JSON_UTF8)
        )
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.username").value("mrcode"))
        ;
    }

这里status()是导入了静态方法,所以不需要写具体类名了

获取用户详情api编写

// 获取用户详情
    // 在路径中使用参数
    @RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
    public User getInfo(@PathVariable String id) {
        User user = new User();
        user.setUsername("mrcode");
        return user;
    }

@PathVaria 说明

用来标识路径中有动态参数,并且我们需要获取到该值;很简单的查看源码,

  • 提供别名和路径中一致。默认路径中的名称和方法入参一致
  • 该参数是否必须

在路径中使用正则表达式

编写测试用例,养成好的习惯;编写边界测试

// 获取用户详情,传递id不为数字,失败测试
@Test
public void whenGetInfoFail() throws Exception {
    mockMvc.perform(get("/user/a")
            .contentType(MediaType.APPLICATION_JSON_UTF8)
    )   
            // 返回结果为 404
            .andExpect(status().is4xxClientError())
    ;
}

把api的路径映射修改,添加正则表达式,只允许数值;
这里是一个简单的正则,只允许数值;
运行测试用例后,返回了404;是因为不是数值,没有匹配上正确的路径

    @RequestMapping(value = "/user/{id:\\d+}", method = RequestMethod.GET)

@JsonView 使用

@JsonView的使用场景:假设有这样一个场景,查询列表和查询详情使用的同一个dto,但是他们
返回的结果字段不是一样的比如:

  • 查询列表中不返回密码
  • 查询详情中需要返回密码

@JsonView 使用步骤

  • 使用接口来声明多个视图
  • 在值对象的get方法上指定视图

    经过测试:放在属性上也有效果

  • 在Contrpller方法上指定视图

声明多个视图

public class User {
    // 简单视图
    public interface UserSimpleView{}
    // 详细视图
    public interface UserDetailView extends UserSimpleView{}

对不同的场景视图设置

@JsonView(UserSimpleView.class)
public String getUsername() {
    return username;
}

@JsonView(UserDetailView.class)
public String getPassword() {
    return password;
}

在controller上设置使用不同的视图;如果这里声明了指定的视图,但是dto里面没有标注任何字段,则返回空串,也就是过滤了所有的返回值

@RequestMapping(value = "/user", method = RequestMethod.GET)
@JsonView(User.UserSimpleView.class)
public List<User> query(UserQueryCondition condition)

@RequestMapping(value = "/user/{id:\\d+}", method = RequestMethod.GET)
@JsonView(User.UserDetailView.class)
public User getInfo(@PathVariable String id) {

编写测试用例,打印返回的结果对比

@Test
public void whenGetInfoSuccess() throws Exception {
    String contentAsString = mockMvc.perform(get("/user/1")
            .contentType(MediaType.APPLICATION_JSON_UTF8)
    )
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.username").value("mrcode"))
            // 获取到返回的结果,然后转换成字符串
            .andReturn().getResponse().getContentAsString();
    System.out.println(contentAsString);
}
// query 方法返回的结果
[{"username":null},{"username":null},{"username":null}]

// getInfo 返回的结果
{"username":"mrcode","password":null}

使用变体映射简化代码

@RestController
@RequestMapping("/user")
public class UserController {
    @GetMapping
    @JsonView(User.UserSimpleView.class)
    public List<User> query(UserQueryCondition condition) {

    @GetMapping("/{id:\\d+}")
    @JsonView(User.UserDetailView.class)
    public User getInfo(@PathVariable String id) {  

再次运行测试之前的测试用例发现一切正常;注意:类上的@RequestMapping("/user") 不要把值直接写在@RestController中了

猜你喜欢

转载自blog.csdn.net/mr_zhuqiang/article/details/81666462