SpringBoot中@RestController,@RequestMapping, @PathVariable,@RequestParam,@GetMapping ,@PostMappin使用

1.@RestController

Spring4之后新加入的注解,原来返回json需要@ResponseBody和@Controller配合。

所以@RestController是@ResponseBody和@Controller的组合注解。

以下两个代码的功能是一样的。

2.@RequestMapping配置url映射

@RequestMapping注解可以作用于控制器的某个方法上,也可以作用于某个控制器的类上面,看以下列子。

(1).作用在类上面;通过http://localhost:8099/springboottest/hello正常访问

(2),作用在方法上面,通过http://localhost:8099/springboottest/hello正常访问


(3)作用在类跟方法上面 http://localhost:8099/springboottest/hello/world

3.@PathVariable 获取URL中的数据


访问url:http://localhost:8099/springboottest/hello/100/world

当然也可以放在类上面,此时的访问路径是url:http://localhost:8099/springboottest/100/hello/world


4.@RequestParam获取请求参数的值


请求结果:http://localhost:8099/springboottest/hello/world?id=100


但是如果请求url中为http://localhost:8099/springboottest/hello/world?id=

或者http://localhost:8099/springboottest/hello/world?id=null

或者http://localhost:8099/springboottest/hello/world,如下图所示就会报错


这时候我们把这个参数可以设置成是否必传。


required 是否必传  defaultValue 默认值(值为字符)

请求结果


5@GetMapping ,@PostMapping   组合注解

@GetMapping(value="/world")  就相当于

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

@PostMapping(value="/world"

@RequestMapping(value = "/world",method = RequestMethod.POST)

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值