在下面的示例中,我试图理解 @RequestMapping 和 @PostMapping 之间的区别。 对于@RequestMapping:
当我执行 POST 请求时:
http://localhost:8085/call1/initparam1?val=1111通过 postman ,它可以正确执行。
但是当它通过 GET 请求进行时
http://localhost:8085/call1/getparam1
我没有得到 1111 结果。
对于@PostMapping,当我执行 POST 请求时:
http://localhost:8085/call1/initparam2/1999通过 postman ,它可以正确执行。
但是当它通过 GET 请求进行时
http://localhost:8085/call1/getparam1
我没有得到 1999 结果。
请向我解释一下使用这两种注释之间有什么区别,因为我花了时间进行谷歌搜索和研究,但我无法弄清楚为什么第一个示例不起作用。
Controller 1
@Controller
@ResponseBody
@RequestMapping("/call1")
public class Call1 {
public String str = "inti";
@RequestMapping(value = "/initparam1", method = RequestMethod.POST)
public void initparam1(@RequestParam(value = "val") String val) {
this.str = val;
}
@PostMapping(value = "/initparam2/{val}")
public void initparam2(@PathVariable String val) {
this.str = val;
}
@RequestMapping("/getparam1")
@ResponseBody
public String getParam1() {
return this.str;
}
}
最佳答案
来自@PostMapping
文档:
Specifically, @PostMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.POST).
因此,只是方便注释更加“详细”,并指示用它注释的方法用于处理 POST HTTP 请求。
我刚刚使用 2.1.4
spring boot 版本检查了您的 Controller 方法,并且您的场景按预期工作,因此您的配置或发送请求的方式一定有问题。
关于java - @RequestMapping 和 @PostMapping 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57025328/