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

匿名 (未验证) 提交于 2019-12-03 00:37:01

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,如下图所示就会报错


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


请求结果



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

@PostMapping(value="/world"

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!