浅谈@RequestMapping和@GetMapping等其他请求注解的区别

区别一:

  1. @GetMapping :

是用于将HTTP get请求映射到特定处理程序的方法注解具体来说,@GetMapping是一个组合注解,是@RequestMapping(method = RequestMethod.GET)的缩写。

  1. @PostMapping :

是用于将HTTP post请求映射到特定处理程序的方法注解具体来说,@PostMapping是一个组合注解,是@RequestMapping(method = RequestMethod.POST)的缩写

  1. @RequestMapping:

一般情况下都是用@RequestMapping(method=RequestMethod.),因为@RequestMapping可以直接替代以上两个注解,但是以上两个注解并不能替代@RequestMapping,@RequestMapping相当于以上两个注解的父类!

  1. 类似的组合注解还有:

@PutMapping、@DeleteMapping、@PatchMapping

5. 总结:

@PostMapping和@GetMapping都可以用@RequestMapping代替,如果读者怕在映射的时候出错,可以统一写@RequestMapping,当然这样写的话也有弊端,笼统的全用@RequestMapping, 不便于其他人对代码的阅读和理解!还是建议区分开来写!养成良好的代码习惯!

@GetMapping注解和@RequestMapping注解的示例:

检验第一个使用的是@GetMapping,第二个使用的是@RequestMapping:

 @GetMapping("/getRule")
    public Rule getRule(){
        Rule rule=new Rule(" @GetMapping","404");
        return rule;
    }
 
    @RequestMapping(method = RequestMethod.GET  ,value = "/getRule2")
    public Rule getRule2(){
        Rule rule=new Rule("@RequestMapping(method = RequestMethod.GET ","404");
        return rule;
    }

使用的是GetMapping

使用的是@RequestMapping

区别二:

@GetMapping 通过 @RequestParam 获取参数

例如:@RequestParam("id") String id, @RequestParam("name")String name

虽然说@GetMapping 注解@RequestMapping注解的组合体,但是@RequestMapping注解不需要@RequestParam 来获取参数,可直接用参数名称获取

@RequestMapping(value = "updateNameById", method = RequestMethod.GET)

区别三:

@RequestMapping注解当我们不设置 method 请求方式 是get 还是 post 的时候,我们需要注意的是:GET,POST 都可以访问

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值