eg:
@GetMapping("/get")
public User getUserById(Integer id) {
if (id.intValue() == 0) {
return null;
}
return list.get(id);
}
HTTP 请求路径= http://ip:port/xx/get?id=1
eg:
@GetMapping("/get")
public User getUserById(@RequestParam(name = "id", required = true) Integer id) {
if (id.intValue() == 0) {
return null;
}
return list.get(id);
}
注意:RequestParam中name表示url中请求的字段名,当required为true时,表示该参数必填;defaultValue表示当该参数没有传递数据时给出的默认值,如defaultvalue=”0”
HTTP 请求路径= http://ip:port/xx/get?id=1
eg:
@GetMapping("/get/{id}")
public User getUserByPathValue(@PathVariable(name = "id", required = true) Integer id)
{
return list.get(id);
}
注意:该方式用来获取路径中的参数。@PathVariable中的字段含义同RequestParam
HTTP 请求路径= http:///ip:port/xx/get/1 ——->对应于http:///ip:port/xx/get/{id}
eg:
@GetMapping("/get")
public User getUserById(HttpServletRequest request) {
Integer id = Integer.parseInt(request.getParameter("id"));
if (id.intValue() == 0) {
return null;
}
return list.get(id);
}
HTTP 请求路径=http://ip:port/xx/get?id=1
温馨提示:一般而言,post形式的参数被放在请求体中以application/json的形式被后端获取
Headers 头部信息设置
SpringMVC 后台Controller层
@PostMapping("/save")
public User saveUser(@RequestBody User user) {
list.add(user);
return user;
}
Postman 模拟请求截图
Headers 头部信息设置
SpringMVC 后台Controller层
@PostMapping("/save")
public User saveUser(@RequestBody Map map) {
Integer id = (Integer) map.get("id");
String name = (String) map.get("name");
Integer age = (Integer) map.get("age");
List hobby=(List) map.get("hobby");
User user = new User(id, name, age, hobby);
list.add(user);
return user;
}
Postman 模拟请求截图
Headers 头部信息设置
SpringMVC 后台Controller层
@PostMapping("/save")
public User save(HttpServletRequest request) {
Integer id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
Integer age = Integer.parseInt(request.getParameter("age"));
String parameter = request.getParameter("hobby");
User user = new User(id, name, age, null);
list.add(user);
return user;
}
Postman 模拟请求截图
Headers 头部信息设置
SpringMVC 后台Controller层
@PostMapping("/save")
public User save(HttpServletRequest request) throws IOException, JSONException {
JSONObject jsonObject = handlerData(request);
Integer id = jsonObject.getInteger("id");
String name = jsonObject.getString("name");
Integer age = jsonObject.getInteger("age");
List hobby = jsonObject.getObject("hobby", List.class);
User user = new User(id, name, age, hobby);
list.add(user);
return user;
}
//这里使用的是alibaba的json工具类
public static JSONObject handlerData(HttpServletRequest request) throws IOException, JSONException {
StringBuffer sb = new StringBuffer();
InputStream is = request.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
String s = "";
while ((s = br.readLine()) != null) {
sb.append(s);
}
if (sb.toString().length() <= 0) {
return null;
} else {
return JSONObject.parseObject(sb.toString());
}
}
Postman 模拟请求截图