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 ...
随机推荐
- 【原创】数据库基础之Mysql(3)mysql删除历史binlog
mysql开启binlog后会在/var/lib/mysql下创建binlog文件,如果手工删除,则下次mysql启动会报错: mysqld: File './master-bin.000001' n ...
- Bootstrap 固定底部导航栏菜单
直接上代码: <!DOCTYPE html> <html> <head> <meta http-equiv="content-type" ...
- GoLand使用
# 不定期更新 什么是GoLand GoLand是JetBrains出品的一个Go语言IDE,JB的IDE有多好用我想很多程序员都知道,个人感觉唯一的缺点就是比较大(因为功能多) 希望大家多多支持正版 ...
- Python-递归、三元表达式列表生成式等
一.函数递归 1.什么是函数递归:函数的递归调用是函数嵌套的一种特殊形式,在调用一个函数的过程中又直接或者间接地调用该函数本身,称之为函数的递归调用 2.递归调用必须明确的两个阶段: 1.回溯:一次次 ...
- Python split()
split翻译为分裂. split()就是将一个字符串分裂成多个字符串组成的列表. split()当不带参数时以空格进行分割,当代参数时,以该参数进行分割. //---当不带参数时 example: ...
- Python 队列
import multiprocessing import time if __name__ == '__main__': # 创建消息队列 # 3: 表示消息队列最大个数 queue = multi ...
- DML_DDL_触发器
Oracle触发器1-介绍Oracle官方参考:PL/SQL Language Referenc->9 PL/SQL TriggerReasons to Use Trigger:■ Automa ...
- vue v-show绑定
在Vue中使用v-show指令来选择性的显示内容.它的属性值可以是布尔值.属性名称以及函数名称.如果使用函数来控制的话,无论函数内容如何运算判断,最终返回布尔值true或者false就可以了 < ...
- 学习promise
总概括 promise是js异步编程的一种解决方案 我对promise的认识(通俗):给一个承诺promise,如果未来发生的事情(异步操作)是符合满足相应条件,则接受resolve,否则失败reje ...
- 体验go语言的风骚式编程
最近想搞搞后台开发,话说注意力就转移到了公司用的golang.用Go做微服务比较方便,或许是因为golang强悍的语法吧,看到go的语法,自己已被深深的吸引.关于学习后台如何选择可以参考<做后台 ...