引言:postman测试接口案例,本文所使用的是网页版的postman。
1. 后端采用@RequestBody接收
(1)post + @RequestBody,接收JSON字符串
Content-type: application/json是将json对象转换为json字符串,@RequestBody注解接收的是json字符串
@PostMapping("/address") public Address save(@RequestBody Address address){ System.out.println("address = " + address); return address; }
(2)post + 默认
// 实体中createTime采用了@DateTimeFormat(pattern = "yyyy-MM-dd")注解 @PostMapping("/address1") public Address save1(Address address){ System.out.println("address = " + address); return address; }
2. 后端采用@RequestParam接收
(1)post + @RequestParam,接收JSON对象
采用此种方式时,前端会把参数拼接为:路径 + ?id=1&addressName=%E5%AE%98%E8%B4%A4&createTime=2019-08-23的形式
@PostMapping("/address2") public Address save2(@RequestParam(name = "addressName") String addressName, @RequestParam(name = "id")Long id, @RequestParam("createTime")String createTime) throws ParseException { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date createData = dateFormat.parse(createTime); Address address = new Address().setAddressName(addressName).setId(id).setCreateTime(createData); System.out.println(addressName); return address; }
(2)get + @RequerstParam/默认
/** * 访问路径:http://localhost:8080/address/1 * 不能以:http://localhost:8080/address?id=1 的方式访问 * @param id * @return */ @GetMapping("/address/{id}") public Address getAddress(@PathVariable("id") Long id){ Optional<Address> addressOptional = addressRepository.findById(id); return addressOptional.orElse(new Address()); } /** * 前端以GET的方式提交 * 访问: * @param id * @return */ @GetMapping("/get") public Address getAddress1(Long id){ Optional<Address> addressOptional = addressRepository.findById(id); return addressOptional.orElse(new Address()); }
参考: