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)