java - @RequestMapping 和 @PostMapping 有什么区别

标签 java spring spring-boot spring-annotations

在下面的示例中,我试图理解 @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/

相关文章:

java - Qartz 正则表达式接受 cron 但不会从中构建作业

java fx 8 可以替代 flex

java - Spring MVC 可以捕获异常并在所有 Controller 的响应中返回 BindingResult 吗?

java - 我可以更改 Swagger 显示的默认定义吗?

java - J2EE 中的容器究竟是什么,它有什么帮助?

java - Button.performClick() 不起作用

java - 如何在终止前调用容器中每个 bean 的销毁方法

java - Spring boot - 由于缺少 EmbeddedServletContainerFactory bean,无法启动 EmbeddedWebApplicationContext

spring-boot - Spring Boot Web 应用程序未启动

java - 找不到路径时如何返回状态码 400