【问题标题】:What is the difference between @RequestMapping and @PostMapping@RequestMapping 和 @PostMapping 有什么区别
【发布时间】:2019-11-23 07:19:41
【问题描述】:

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

【问题讨论】:

  • 如果我错了请纠正我,但我的理解是你的第一个例子是不工作,第二个例子是正常工作。因为在这两种情况下,您都写了 'I don't get...'
  • 两种方案都在 GET 请求中设置并返回各自的值。我已经检查了 Spring Boot 2.1.6 版本。
  • RequestMapping 与此处讨论的特定 Get/Post 映射stackoverflow.com/questions/39077787/…

标签: java spring spring-boot spring-annotations


【解决方案1】:

来自@PostMapping 文档:

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

所以只有方便注释更“冗长”,并表明使用它注释的方法用于处理 POST HTTP 请求。

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

【讨论】:

  • 但你是否意识到了任务的另一部分。请。使用 POSTMAPPING 给了我预期的结果,但 REQUESTMAPPING 给了我意想不到的结果
  • 我刚刚检查了您的设置,它按预期工作,两个端点都设置了您的字符串的值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-16
  • 1970-01-01
  • 2010-10-02
  • 2011-12-12
  • 2010-09-16
  • 2012-03-14
  • 2012-02-06
相关资源
最近更新 更多