Spring MVC中@JsonView的使用
一、@JsonView注解的简介
@JsonView是jackson json中的一个注解,Spring webmvc也支持这个注解,它的作用就是控制输入输出后的json
二、@JsonView注解的使用步骤
1.使用接口来声明多个视图
package com.knyel.dto;
public class User {
public interface UserSimpleView {};
public interface UserDetailView extends UserSimpleView {};
private String username;
private String password;
public String getUsername (){
return username;
}
public void setUsername (String username){
this.username = username;
}
public String getPassword (){
return password;
}
public void setPassword (String password){
this.password = password;
}
@Override
public String toString (){
return "User{" + "username='" + username + '\'' + ", password='" + password + '\'' + '}';
}
}
2.在值对象的get方法上指定视图
package com.knyel.dto;
import com.fasterxml.jackson.annotation.JsonView;
public class User {
public interface UserSimpleView {};
public interface UserDetailView extends UserSimpleView {};
private String username;
private String password;
@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 + '\'' + '}';
}
}
3.在controller方法上指定视图
package com.knyel.wb.controller; import com.fasterxml.jackson.annotation.JsonView;
import com.knyel.dto.User;
import com.knyel.dto.UserQueryCondition;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.data.domain.Pageable; import java.util.ArrayList;
import java.util.List; @RestController
public class UserController {
@RequestMapping(value = "/user",method = RequestMethod.GET)
@JsonView(User.UserSimpleView.class)
public List<User> query(UserQueryCondition userQueryCondition, @PageableDefault(page=1,size=10,sort="username,asc") Pageable pageable){
System.out.println(pageable.getPageNumber());
System.out.println(pageable.getSort());
System.out.println(pageable.getPageSize());
System.out.println(userQueryCondition.toString());
List<User> users=new ArrayList<>();
users.add(new User());
users.add(new User());
users.add(new User());
return users;
}
@RequestMapping(value="/user/{id:\\d+}",method = RequestMethod.GET)
@JsonView(User.UserDetailView.class)
public User getInfo(@PathVariable String id){
User user=new User();
user.setUsername("knyel");
System.out.println(user);
return user;
}
}
4.测试类
package com.knyel.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 wac; private MockMvc mockMvc; @Before
public void setUp (){
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
} @Test
public void whenQuerySuccess () throws Exception{
String result=mockMvc.perform(MockMvcRequestBuilders.get("/user")
.param("username","knyel")
.param("age","18")
.param("ageTo","60")
.param("phone","110")
.param("size","15")
.param("page","2")
.param("sort","age,desc")
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.length()").value("3"))//查询的根元素,例如$.length()代表整个传过来的json的文档
.andReturn().getResponse().getContentAsString();
System.out.println(result);
} @Test
public void whenGenInfoSuccess() throws Exception{
String result=mockMvc.perform(MockMvcRequestBuilders.get("/user/1")
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.username").value("knyel"))
.andReturn().getResponse().getContentAsString();
System.out.println(result);
} @Test
public void whenGetInfoFail() throws Exception{
mockMvc.perform(MockMvcRequestBuilders.get("/user/a")
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(MockMvcResultMatchers.status().is4xxClientError());
}
}
whenQuerySuccess的返回值为:
[{"username":null},{"username":null},{"username":null}]
whenGetInfoSuccess的返回值为:
{"username":"knyel","password":null}
对于带有分页查询的例子
@Test
public void whenGetDwbzxxSuccess() throws Exception{ String result=mockMvc.perform(MockMvcRequestBuilders.get("/dwbzxx/findDwbzxx")
.param("limit", "10")
.param("offset", "0")
.param("dwdmYj", "1399")
.param("dwdmEj", "28e516432383411b8fac66a2b8ff08bf")
.contentType(MediaType.APPLICATION_JSON))
.andReturn().getResponse().getContentAsString(); System.out.println(result);
}
Spring MVC中@JsonView的使用的更多相关文章
- Spring mvc中@RequestMapping 6个基本用法
Spring mvc中@RequestMapping 6个基本用法 spring mvc中的@RequestMapping的用法. 1)最基本的,方法级别上应用,例如: Java代码 @Reques ...
- spring mvc中使用freemark的一点心得
参考文档: FreeMarker标签与使用 连接http://blog.csdn.net/nengyu/article/details/6829244 freemarker学习笔记--指令参考: ht ...
- Http请求中Content-Type讲解以及在Spring MVC中的应用
引言: 在Http请求中,我们每天都在使用Content-type来指定不同格式的请求信息,但是却很少有人去全面了解content-type中允许的值有多少,这里将讲解Content-Type的可用值 ...
- Spring mvc中@RequestMapping 6个基本用法小结(转载)
小结下spring mvc中的@RequestMapping的用法. 1)最基本的,方法级别上应用,例如: @RequestMapping(value="/departments" ...
- Spring MVC中处理静态资源的多种方法
处理静态资源,我想这可能是框架搭建完成之后Web开发的”头等大事“了. 因为一个网站的显示肯定会依赖各种资源:脚本.图片等,那么问题来了,如何在页面中请求这些静态资源呢? 还记得Spring MVC中 ...
- Spring MVC 中的基于注解的 Controller【转】
原文地址:http://my.oschina.net/abian/blog/128028 终于来到了基于注解的 Spring MVC 了.之前我们所讲到的 handler,需要根据 url 并通过 H ...
- spring mvc中的文件上传
使用commons-fileupload上传文件所需要的架包有:commons-fileupload 和common-io两个架包支持,可以到Apache官网下砸. 在配置文件spring-mvc.x ...
- spring mvc中的valid
当你希望在spring mvc中直接校验表单参数时,你可以采用如下操作: 声明Validator的方式: 1.为每一个Controller声明一个Validator @Controller publi ...
- spring mvc中的@PathVariable(转)
鸣谢:http://jackyrong.iteye.com/blog/2059307 ------------------------------------------------ spring m ...
随机推荐
- Android 的内存泄露和内存限制
转载自 https://blog.csdn.net/goodlixueyong/article/details/40716779 https://blog.csdn.net/vshuang/artic ...
- 在他机上还原DB2的备份
在服务器获取得到db2的备份文件,拷贝到d盘db2_backup目录下面 在windows下的时间戳标记为时间目录名+文件名.001前面的 "2014022\0001006.001" ...
- C# 自定义类动态追加属性
利用Dynamic,需要.net4.0以上的支持 var dg = rel.ResultDocuments.FirstOrDefault()["dg"].AsBsonArray.G ...
- Linux报错:bash: pip: command not found
$ wget https://bootstrap.pypa.io/get-pip.py$ python get-pip.py$ pip -V #查看pip版本 接下来就可以随便pip安装东西了
- QQ第三方登录(完结篇)
书接上回,上回说到:这篇是代码篇 首先我们先来看一下我的母鹿(目录)吧 Connect2.1 是我们从下载的SDK,内容包含 其他文件在配置之后全部删除了! index.html 是我们点击登陆的页 ...
- for...in的改进版for...of
for...in 用起来似乎还不错,为什么又弄个 for...of 呢? 来看个例子: 'user strict' var arr = [12,13,14,15,16]; for(var i in a ...
- Mysql数据表去重
查询不重复元素个数 select count(distinct domain) from black_botnet_domian; 查询表中元素个数大于等于2的元素 SELECT goods_id,g ...
- 【机器学习_5】Anaconda:初学Python、入门机器学习的首选
Anaconda是一个用于科学计算的Python发行版,提供了包管理与环境管理的功能,可以很方便地解决多版本python并存.切换以及各种第三方包安装问题. 集成包功能: NumPy:提供了矩阵运算的 ...
- py库:文本转为语音(pywin32、pyttsx)
http://blog.csdn.net/marksinoberg/article/details/52137547 Python 文本转语音 文本转为语音(使用Speech API) 需要安装 py ...
- JDK1.7 高并发下的HashMap
HashMap的容量是有限的.当经过多次元素插入,使得HashMap达到一定饱和度时,Key映射位置发生冲突的几率会逐渐提高. 这时候,HashMap需要扩展它的长度,也就是进行Resize. 影响发 ...