前言
Postman是一款Http请求模拟工具.它可以模拟各种Http Request,使用起来十分的方便.
使用背景
利用Spring Boot 快速搭建一个Web应用,利用相同的url,不同的请求方式来调用不同的方法.最后利用Postman工具模拟实现.
实现方法
- 利用IDEA快速构建应用环境
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies>
- 配置SpringBoot文件application.yml
server:
port: 8080
servlet:
context-path: /girl
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/test
driver-class-name: com.mysql.jdbc.Driver
username: root
password: 1234
jpa:
hibernate:
ddl-auto: update
show-sql: true
- Controller代码
@RestControllerpublicclassMyController {@Autowired
UserDao userDao;@RequestMapping(value ="/say/{name}")public @ResponseBody Usersay(@PathVariable("name") String uname){
User user =new User();
user.setUname(uname);return userDao.save(user);
}@GetMapping("/a")public List<User>geyUserList(){return userDao.findAll();
}@PostMapping("/a")public UseraddUser(@RequestParam("uname") String uname){
User user =new User();
user.setUname(uname);return userDao.save(user);
}@PutMapping(value ="/a/{no}")public UserupdateUser(@PathVariable("no") Integer uno,@RequestParam("uname") String uname){
User user =new User();
user.setUno(uno);
user.setUname(uname);return userDao.save(user);
}@DeleteMapping(value ="/a/{no}")publicvoiddeleteUser(@PathVariable("no") Integer uno){
userDao.deleteById(uno);
}
}
其中需要说明的几个注解:
GetMapping/PostMapping/PutMapping/DeleteMapping都是组合注解.
学习过SpringMVC的同学都知道用RequestMapping注解来进行映射请求.
而以上四个注解就是基于Http的REST风格的请求+RequestMapping的结合.
分别代表REST风格的CRUD操作.
使用Postman
下载方式:chrome商店搜索Postman即可.(有问题可以来私信我)
如下图所示,Postman界面为我们提供了多种请求方式
举个栗子
利用Put请求使用更新操作
首先选择请求方式为Put,在Body标签下填写要传入的参数,需要注意的是Put请求与其他三种请求方式不一样,要选择x-www-form-urlencoded方式提交,而不是form-data.
- 详细的Postman教程,我推荐点火三周的博文