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 ...
随机推荐
- tcp协议简单了解
HTTP简介 HTTP协议是Hyper Text Transfer Protocol(超文本传输协议)的缩写,是用于从万维网(WWW:World Wide Web )服务器传输超文本到本地浏览器的传送 ...
- yun
# Author:zhang# -*- coding:utf-8 -*-"""https://workyun.com/ 云端工作"""imp ...
- IOS 颜色的宏定义
#define RGB(r, g, b, a) [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a] self.vie ...
- Confluence 6 用户目录图例 - 连接 Jira 和 Jira 连接 LDAP
上面的图: Confluence 连接到 JIRA 用户管理,JIRA 使用 LDAP 用户目录. https://www.cwiki.us/display/CONFLUENCEWIKI/Diagra ...
- Layer-level的快速算法
十岁的小男孩 本文为终端移植的一个小章节. Sparse Block Net 本节为优化加速的第二章节,主要介绍Sparse-block net.上章节为OP算子层的加速,本节为层级间的加速,主要针对 ...
- Linux 编程笔记(四)
一.用户和用户组管理 添加新的用户账户使用useradd 格式useradd 选项 用户名 1.创建一个用户tian 其中 -d -m参数用来为登陆,登录名产生一个主目录 /usr/tian(其 ...
- python进行进制转换
# 10进制转为2进制 print(bin(10)) # 结果:0b1010 # 2进制转为10进制 print(int("1001", 2)) # 结果:9 # 10进制转为16 ...
- Jmeter中常用的一些对字符串的处理
1)截取部分线程组的名称 group = ctx.getThreadGroup(); // 获取当前线程组 str = group.getName(); // 获取线程组的名称 str = str.s ...
- selenium+python-autoit文件上传
前言 关于非input文件上传,点上传按钮后,这个弹出的windows的控件了,已经跳出三界之外了,不属于selenium的管辖范围(selenium不是万能的,只能操作web上元素).autoit工 ...
- C++ Primer 笔记——动态数组
1.动态数组定义时也需要指明数组的大小,但是可以不是常量. int i; int arr[i]; // 错误,数组的大小必须为常量 int *p = new int[i]; // 正确,大小不必是常量 ...