@JsonView了解

@JSONVIEW注解的使用(查看的是别人的,自己只是作为笔记)
看到一个新的注解以前没有用过,记录一下使用方法。

注意是:com.fasterxml.jackson.annotation.JsonView
@JsonView可以过滤pojo的属性,使Controller在返回json时候,pojo某些属性不返回,比如User的密码,一般是不返回的,就可以使用这个注解。

@JsonView使用方法:

1,使用接口来声明多个视图

2,在pojo的get方法上指定视图

3,在Controller方法上指定视图

例子:条件查询时候不返回用户的密码,查看详情时候返回用户的密码

User:

复制代码
package com.imooc.dto;

import com.fasterxml.jackson.annotation.JsonView;

public class User {

public interface UserSimpleView {};  
public interface UserDetailView extends UserSimpleView{}; //继承

private String username;

private String password;

//UserSimpleView视图有
@JsonView(UserSimpleView.class)
public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}
@JsonView(UserDetailView.class)
public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

@Override
public String toString() {
    return "User [username=" + username + ", password=" + password + "]";
}        

}
复制代码
Controller:

复制代码
package com.imooc.web.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.annotation.JsonView;
import com.imooc.dto.User;
import com.imooc.dto.UserQueryCondition;

@RestController
@RequestMapping("/user")
public class UserController {

/**
 * @Description: 条件查询
 * @param @param condition
 * @param @param pageable
 * @param @return   
 * @return List<User>  
 * @throws
 * @author lihaoyang
 * @date 2018年2月24日
 */
@GetMapping("query")
@JsonView(User.UserSimpleView.class)
public List<User> query(
        //@RequestParam(value="username",required=false,defaultValue="lhy") String username
        UserQueryCondition condition , Pageable pageable){

// System.err.println(username);
System.err.println(condition.toString());
System.err.println(pageable.toString());

    List<User> users = new ArrayList<User>();
    users.add(new User());
    users.add(new User());
    users.add(new User());
    return users;
}

/**
 * 详情
 * @Description: TODO
 * @param @param id
 * @param @return   
 * @return User  
 * @throws
 * @author lihaoyang
 * @date 2018年2月24日
 */
@GetMapping("detail/{id:\\d+}") //{}里可以是正则,匹配数字

// @GetMapping(“detail/{id}”)
@JsonView(User.UserDetailView.class)
public User getInfo(@PathVariable(value=“id”,required=true) String id){
System.err.println(id);
User user = new User();
user.setUsername(“tom”);
return user;
}

}
复制代码
测试用例:

复制代码
package com.imooc.web.controller;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserControllerTest {

@Autowired
private WebApplicationContext webCtx;

//伪造mvc
private MockMvc mockMvc;

@Before
public void setup(){
    mockMvc = MockMvcBuilders.webAppContextSetup(webCtx).build();
}

/**
 * 查询
 */
@Test
public void whenQuerySuccess() throws Exception{
    String result = mockMvc.perform(MockMvcRequestBuilders.get("/user/query") //路径
            .param("page", "10")   //参数
            .param("size", "12")
            .param("sort", "age,desc")
            .param("username", "xiaoming") 
            .param("age", "18")
            .param("ageTo", "40")
            .param("other", "otherProperty")
            .contentType(MediaType.APPLICATION_JSON_UTF8))
            .andExpect(MockMvcResultMatchers.status().isOk()) //状态码200
            .andExpect(MockMvcResultMatchers.jsonPath("$.length()").value(3))//长度为3,具体查看github的jsonPath项目    
            .andReturn().getResponse().getContentAsString();
    System.err.println(result);
}

/**
 * 详情
 */
@Test
public void whenGetInfoSuccess() throws Exception{
    String result = mockMvc.perform(MockMvcRequestBuilders.get("/user/detail/1")
            .contentType(MediaType.APPLICATION_JSON_UTF8))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.jsonPath("$.username").value("tom"))
            .andReturn().getResponse().getContentAsString();
    System.err.println(result);
}

/**
 * 详情失败
 */
@Test
public void whenGetInfoFail() throws Exception{
    mockMvc.perform(MockMvcRequestBuilders.get("/user/detail/a") //匹配正则
            .contentType(MediaType.APPLICATION_JSON_UTF8))
            .andExpect(MockMvcResultMatchers.status().is4xxClientError());
            
}

}
复制代码

打印结果:使用UserDetailView视图的会把密码给打印出来

原文地址:https://www.cnblogs.com/lihaoyang/p/8464517.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值