一,post对应参数类型注解
RequestBody
PathVariable
RequestParam
二,body为表单格式的post请求
2.1 代码示例:
/ 登录请求路径:http://localhost:8080/login
// 对应body体为表单提交格式:{"username":{username},"password":{password}}
@PostMapping(value = "/login")
// String login(String username , String password){
// return "用户名:{" + username + "},密码为:{" + password + "}" ;
// }
2.2 通过postman来查看接口请求是否成功:
三,body为json格式的post请求
3.1 代码示例:
// 登录请求路径:http://localhost:8080/login
// 接收请求参数为实体类,而非字符串,使用@RequestBody绑定前端传参和后端参数
//produces:申请传递参数的类型为json,如果不申明json,在postman请求时会报415
@PostMapping(value = "/login", produces = "application/json")
String login(@RequestBody UserDto userDto){
if(userDto.getUsername().equals("demi") && userDto.getPassword().equals("123456")){
return "用户登录成功!用户名:" + userDto.getUsername() + ", 密码:" +userDto.getPassword();
}else{
return "用户登录失败!用户名:" + userDto.getUsername() + ", 密码:" +userDto.getPassword();
}
}
3.2 通过postman来查看接口请求是否成功:
四,body为json提交格式的post请求
4.1 代码示例:
// 注册请求路径:http://localhost:8080/{module}/register?desc={desc}&age={age}
// 对应body体为json提交格式:{"username":{username},"password":{password}}
@PostMapping(path = "/{module}/register", produces = "application/json")
String registerAndParam(@RequestBody UserDto userDto, @PathVariable String module,
@RequestParam String desc, @RequestParam int age){
return "用户登录成功!用户名:" + userDto.getUsername() + ", 密码:" +userDto.getPassword() + ", 模块:"+ module + ", 描述:" +desc + ", 年龄:" +age;
}
4.2 通过postman来查看接口请求是否成功:
-
params传参:
-
body传参:
五,body为xml提交格式的post请求
5.1 导入依赖
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.13.1</version>
</dependency>
5.2 新建实体类文件,并加上xml根注解标签 @JacksonXmlRootElement
package com.ceshiren.springtest.dto;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import lombok.Data;
@Data
//xml根注解标签
@JacksonXmlRootElement
public class XmlDto {
String uname;
String pwd;
}
5.3 代码示例
// 注册请求路径:http://localhost:8080/{module}/register?desc={desc}&age={age}
// 对应body体为xml提交格式: <userxml version="1.0" encoding="UTF-8" > <uname>北京</name> <pwd>2022</age> </userxml>
@PostMapping(value = "/{module}/register", produces = MediaType.APPLICATION_ATOM_XML_VALUE)
String registerAndParamWithXml(@RequestBody XmlDto xmlDto, @PathVariable String module,
@RequestParam String desc, @RequestParam int age){
return "用户登录成功!用户名:" + xmlDto.getUname() + ", 密码:" +xmlDto.getPwd() + ",注册模块:" +module + ", 描述:" +desc + ", 年龄:" +age;
}