@RequestMapping和@PostMapping有什么区别

时间:2019-07-14 07:16:02

标签: java spring spring-boot spring-annotations

在下面的示例中,我试图低估@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。

请给我解释一下,因为我花了很多时间进行谷歌搜索和研究,但是使用这两个注释有什么区别,但我不知道为什么第一个示例不起作用。

Controller1

@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;
}
}

2 个答案:

答案 0 :(得分:1)

来自@PostMapping文档:

  

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

因此,只有方便注释才更加“冗长”,并指示带有注释的方法用于处理POST HTTP请求。

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

答案 1 :(得分:1)

@PostMapping 是一个组合注释,用作@RequestMapping(方法= RequestMethod.POST)的快捷方式。

@PostMapping("/post")
public @ResponseBody ResponseEntity<String> post() {
   return new ResponseEntity<String>("POST Response", HttpStatus.OK);
}

以前,我们必须使用@RequestMapping进行此操作。这种新方法可以缩短它。

Spring当前支持五种内置注释,用于处理不同类型的传入HTTP请求方法,即GET,POST,PUT,DELETE和PATCH。这些注释是:

  • @GetMapping

  • @PostMapping

  • @PutMapping

  • @DeleteMapping

  • @PatchMapping

请检查 Spring @RequestMapping New Shortcut Annotations

相关问题