大家好,又见面了,我是你们的朋友全栈君。
@RequestParam和@RequestBody这两个注解是可以同时使用的。
网上有很多博客说@RequestParam 和@RequestBody不能同时使用,这是错误的。根据HTTP协议,并没有说post请求不能带URL参数,经验证往一个带有参数的URL发送post请求也是可以成功的。只不过,我们日常开发使用GET请求搭配@RequestParam,使用POST请求搭配@RequestBody就满足了需求,基本不怎么同时使用二者而已。
自己个人实际验证结果:
package com.example.model;
import java.util.List;
public class PramInfo {
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
private int id;
private String str;
}
package com.example.demo;
import com.example.model.PramInfo;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(value = "/test")
public class TestContoller {
@RequestMapping(value = "/dxc")
public String print(PramInfo info) {
return info.getId() + ": :" + info.getStr();
}
@RequestMapping(value = "/getUserJson")
public String getUserJson(@RequestParam(value = "id") int id, @RequestParam(value = "name2", required = false) String name2
, @RequestBody PramInfo pramInfo) {
return (id + "--" + name2 + ";paramInfo:" + pramInfo.getStr() + ";pramInfo.id:" + pramInfo.getId());
}
}
@GetMapping(value = "/dxc")
public String print(PramInfo info) {
return info.getId() + ": :" + info.getStr();
}
@PostMapping(value = "/getUserJson")
public String getUserJson(@RequestParam(value = "id") int id, @RequestParam(value = "name2", required = false) String name2
, @RequestBody PramInfo pramInfo) {
return (id + "--" + name2 + ";paramInfo:" + pramInfo.getStr() + ";pramInfo.id:" + pramInfo.getId());
2018-05-12 23:45:27.494 WARN 6768 --- [nio-8080-exec-6] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public java.lang.String com.example.demo.TestContoller.getUserJson(int,java.lang.String,com.example.model.PramInfo)
-05-12 23:45:27.494 WARN 6768 --- [nio-8080-exec-6] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public java.lang.String com.example.demo.TestContoller.getUserJson(int,java.lang.String,com.example.model.PramInfo)
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/148706.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...