003 使用SpringMVC开发restful API--查询用户
一:介绍说明
1.介绍

2.restful api的成熟度

二:编写Restful API的测试用例
1.引入spring的测试框架
在effective pom中查找

2.新建测试包,测试类

3.测试用例程序
package com.cao.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 {
//伪造测试用例,不需要跑tomcat,运行会很快
@Autowired
private WebApplicationContext wac; //伪造的一个mvc环境
private MockMvc mockMvc; @Before
public void setup() {
//初始化这个环境
mockMvc=MockMvcBuilders.webAppContextSetup(wac).build();
} @Test
public void whenQuerySuccess() throws Exception {
//发送请求
mockMvc.perform(MockMvcRequestBuilders.get("/user")
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.length()").value(3));
} }
4.执行效果

三:使用注解声明RestfulAPI
1.常用注解
@RestController标明此controller提供RestAPI
@RequestMapping及其变体,映射url到java
@RequestParam映射请求参数到java方法上的参数、
@PageableDefault指定分页参数默认值
2.@RestController与@RequestMapping小测试
控制类
package com.cao.web.controller; import java.util.ArrayList;
import java.util.List; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; import com.cao.dto.User; //此controller可以提供restful服务
@RestController
public class UserController {
@RequestMapping(value="/user",method=RequestMethod.GET)
public List<User> query(){
List<User> userList=new ArrayList<>();
userList.add(new User());
userList.add(new User());
userList.add(new User());
return userList;
} }
User.java
新建dto包
package com.cao.dto;
public class User {
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;
}
}
3.效果
说明,服务已经建立起来了。

4.@RequestParam小测试【单个参数】
常规的用法
测试类
package com.cao.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 {
//伪造测试用例,不需要跑tomcat,运行会很快
@Autowired
private WebApplicationContext wac; //伪造的一个mvc环境
private MockMvc mockMvc; @Before
public void setup() {
//初始化这个环境
mockMvc=MockMvcBuilders.webAppContextSetup(wac).build();
} @Test
public void whenQuerySuccess() throws Exception {
//发送请求
mockMvc.perform(MockMvcRequestBuilders.get("/user")
.param("username", "Job")
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.length()").value(3));
} }
控制类
package com.cao.web.controller; import java.util.ArrayList;
import java.util.List; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import com.cao.dto.User; //此controller可以提供restful服务
@RestController
public class UserController {
@RequestMapping(value="/user",method=RequestMethod.GET)
public List<User> query(@RequestParam String username){
List<User> userList=new ArrayList<>();
System.out.println("username="+username);
userList.add(new User());
userList.add(new User());
userList.add(new User());
return userList;
} }
RequestParam的其他参数

package com.cao.web.controller; import java.util.ArrayList;
import java.util.List; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import com.cao.dto.User; //此controller可以提供restful服务
@RestController
public class UserController {
@RequestMapping(value="/user",method=RequestMethod.GET)
public List<User> query(@RequestParam(name="username",required=false,defaultValue="Tom") String name){
List<User> userList=new ArrayList<>();
System.out.println("name="+name);
userList.add(new User());
userList.add(new User());
userList.add(new User());
return userList;
} }
这里主要是要注意一下别名。
5.使用类组装多个参数【多个参数进行传递】
这里主要是说上面的RequestParam不再满足的时候,主要的场景是复杂的多请求参数时
测试类
package com.cao.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 {
//伪造测试用例,不需要跑tomcat,运行会很快
@Autowired
private WebApplicationContext wac; //伪造的一个mvc环境
private MockMvc mockMvc; @Before
public void setup() {
//初始化这个环境
mockMvc=MockMvcBuilders.webAppContextSetup(wac).build();
} @Test
public void whenQuerySuccess() throws Exception {
//发送请求
mockMvc.perform(MockMvcRequestBuilders.get("/user")
.param("username", "Job")
.param("age", "18")
.param("xxx", "XXX")
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.length()").value(3));
} }
控制类
package com.cao.web.controller; import static org.mockito.Matchers.contains; import java.util.ArrayList;
import java.util.List; import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import com.cao.dto.User;
import com.cao.dto.UserQueryCondition; //此controller可以提供restful服务
@RestController
public class UserController {
@RequestMapping(value="/user",method=RequestMethod.GET)
public List<User> query(UserQueryCondition condition){
//反射的方法来打印
System.out.println(ReflectionToStringBuilder.toString(condition, ToStringStyle.MULTI_LINE_STYLE));
//
List<User> userList=new ArrayList<>();
userList.add(new User());
userList.add(new User());
userList.add(new User());
return userList;
} }
UserQueryCondition.java
package com.cao.dto;
public class UserQueryCondition {
private String username;
private int age;
private int ageTo;
private String xxx;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getAgeTo() {
return ageTo;
}
public void setAgeTo(int ageTo) {
this.ageTo = ageTo;
}
public String getXxx() {
return xxx;
}
public void setXxx(String xxx) {
this.xxx = xxx;
}
}
效果

6.@Pageable
测试类
package com.cao.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 {
//伪造测试用例,不需要跑tomcat,运行会很快
@Autowired
private WebApplicationContext wac; //伪造的一个mvc环境
private MockMvc mockMvc; @Before
public void setup() {
//初始化这个环境
mockMvc=MockMvcBuilders.webAppContextSetup(wac).build();
} @Test
public void whenQuerySuccess() throws Exception {
//发送请求
mockMvc.perform(MockMvcRequestBuilders.get("/user")
.param("username", "Job")
.param("age", "18")
.param("xxx", "XXX")
//分页,查第三页,每页15条,按照age降序
.param("page", "3")
.param("size", "15")
.param("sort", "age,desc")
//
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.length()").value(3));
} }
控制类
package com.cao.web.controller; import static org.mockito.Matchers.contains; import java.util.ArrayList;
import java.util.List; import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import com.cao.dto.User;
import com.cao.dto.UserQueryCondition; //此controller可以提供restful服务
@RestController
public class UserController {
@RequestMapping(value="/user",method=RequestMethod.GET)
public List<User> query(UserQueryCondition condition,@PageableDefault(size=13) Pageable pageable){
//反射的方法来打印
System.out.println(ReflectionToStringBuilder.toString(condition, ToStringStyle.MULTI_LINE_STYLE));
//
System.out.println(pageable.getPageSize());
System.out.println(pageable.getPageNumber());
System.out.println(pageable.getSort());
//
List<User> userList=new ArrayList<>();
userList.add(new User());
userList.add(new User());
userList.add(new User());
return userList;
} }
效果

003 使用SpringMVC开发restful API--查询用户的更多相关文章
- 006 使用SpringMVC开发restful API四--用户信息的修复与删除,重在注解的定义
一:任务 1.任务 常用的验证注解 自定义返回消息 自定义校验注解 二:Hibernate Validator 1.常见的校验注解 2.程序 测试类 /** * @throws Exception * ...
- 004 使用SpringMVC开发restful API二--编写用户详情
一:编写用户详情服务 1.任务 @PathVariable隐射url片段到java方法的参数 在url声明中使用正则表达式 @JsonView控制json输出内容 二:@PathVariable 1. ...
- 007 使用SpringMVC开发restful API五--异常处理
一:任务 1.任务 Spring Boot中默认的错误机制处理机制 自定义异常处理 二:Spring Boot中的默认错误处理机制 1.目前 浏览器访问的时候, restful 接口主要是根据状态码进 ...
- 005 使用SpringMVC开发restful API三--处理创建请求
一:主要任务 1.说明 @RequestBody 映射请求体到java方法的参数 日期类型参数的处理 @Valid注解 BindingResult验证请求参数的合法性并处理校验结果 二:@Reques ...
- springmvc/springboot开发restful API
非rest的url写法: 查询 GET /user/query?name=tom 详情 GET /user/getinfo? 创建 POST /user/create?name=tom 修改 POST ...
- ASP.NET Core Web API 开发-RESTful API实现
ASP.NET Core Web API 开发-RESTful API实现 REST 介绍: 符合REST设计风格的Web API称为RESTful API. 具象状态传输(英文:Representa ...
- 使用Spring MVC开发RESTful API
第3章 使用Spring MVC开发RESTful API Restful简介 第一印象 左侧是传统写法,右侧是RESTful写法 用url描述资源,而不是行为 用http方法描述行为,使用http状 ...
- flask开发restful api系列(8)-再谈项目结构
上一章,我们讲到,怎么用蓝图建造一个好的项目,今天我们继续深入.上一章中,我们所有的接口都写在view.py中,如果几十个,还稍微好管理一点,假如上百个,上千个,怎么找?所有接口堆在一起就显得杂乱无章 ...
- flask开发restful api
flask开发restful api 如果有几个原因可以让你爱上flask这个极其灵活的库,我想蓝图绝对应该算上一个,部署蓝图以后,你会发现整个程序结构非常清晰,模块之间相互不影响.蓝图对restfu ...
随机推荐
- [C]C语言中的指针和内存泄漏几种情况
引言 原文地址:http://www.cnblogs.com/archimedes/p/c-point-memory-leak.html,转载请注明源地址. 对于任何使用C语言的人,如果问他们C语言的 ...
- Docker架构图
Docker架构图 服务器---主机系统中通过Cgroup和Namespace-----------划分成多个bins/libs---------------每个app运行在独立的bins/libs中 ...
- Codeforces 1132G Greedy Subsequences [线段树]
洛谷 Codeforces 看到题解那么少就来发一篇吧-- 思路 看完题目一脸懵逼,感觉无从下手. 莫名其妙地想到笛卡尔树,但笛卡尔树好像并没有太大作用. 考虑把笛卡尔树改一下:每个点的父亲设为它的右 ...
- Confluence 6 删除垃圾内容
属性(profile)垃圾 属性垃圾的定义为,一个垃圾用户在 Confluence 创建了用户,但是这个用户在自己的属性页面中添加了垃圾 URL. 如果你有很多垃圾用户在你的系统中创建了属性,你可以使 ...
- Confluence 6 WebDAV 禁用严格路径检查
如果你在你的 WebDAV 客户端发现了一些不正常的现象,例如文件夹在 Confluence 中是存在的,但是在你客户端下载的文件中就不存在了.你可以禁用 WebDAV 插件中的严格路径检查选项,这 ...
- bat如何创建多级文件夹(在android设备中)
在android设备中要创建多个或者多级文件夹时,手动去创建费时费力(有点傻),一个bat文件就能很好的实现这个功能. 1.首先创建同级多个文件夹且在该文件夹下生成一个文件 @echo off ech ...
- day34 基于TCP和UDP的套接字方法 粘包问题 丢包问题
TCP 基于流的协议 又叫可靠性传输协议 通过三次握手 四次挥手 来保证数据传输完毕 缺点效率低 正因为是基于流的协议 所以会出现粘包问题粘包问题:原因一:是应为数据是先发送给操作系统,在操作系统中有 ...
- django之跨表查询及添加记录
一:创建表 书籍模型: 书籍有书名和出版日期,一本书可能会有多个作者,一个作者也可以写多本书,所以作者和书籍的关系就是多对多的关联关系(many-to-many); 一本书只应该由一个出版商出 ...
- MySQL5.7.20安装过程报错CMake Error at cmake/boost.cmake:81 (MESSAGE):
MySQL在5.7版本及以后,都需要boots 库,所以需要先安装boots 步骤: 1.在/usr/local下创建 名为boots的目录 mkdir -p /usr/local/boots 2.进 ...
- C和C++ 中的const
C++中的const正常情况下是看成编译期的常量,编译器并不为const分配空间,只是在编译的时候将期值保存在名字表中,并在适当的时候折合在代码中.所以,以下代码: #include <iost ...