@RequestMapping 和@PostMapping 有什么区别

use*_*121 8 java spring spring-annotations spring-boot

在下面的例子中,我试图理解@RequestMapping 和@PostMapping 之间的区别。对于@RequestMapping:

当我通过邮递员执行POST 请求时: http://localhost:8085/call1/initparam1?val=1111,它正确执行。但是当它通过 GET 请求
http://localhost:8085/call1/getparam1 进行时

结果我没有得到 1111。

对于@PostMapping,当我通过邮递员执行POST 请求: http://localhost:8085/call1/initparam2/1999 时,它会正确执行。但是当它通过 GET 请求
http://localhost:8085/call1/getparam1 进行时

结果我没有得到 1999。

请向我解释使用这两种注释有什么区别,因为我花了时间谷歌搜索和研究,但我无法弄清楚为什么第一个例子不起作用。

控制器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;
}
}
Run Code Online (Sandbox Code Playgroud)

mic*_*alk 11

@PostMapping文档:

具体来说,@PostMapping 是一个组合注解,作为@RequestMapping(method = RequestMethod.POST) 的快捷方式。

因此,它只是更“详细”的便利注释,并指示用它注释的方法用于处理 POST HTTP 请求。

我刚刚使用2.1.4spring boot 版本检查了您的控制器方法,并且您的场景按预期工作,因此您的配置或发送请求的方式一定有问题。