1) springMVC常用注解
注解 |
作用域 |
说明 |
`@Controller |
类 |
Controller标识 |
`@RequestMapping |
类/方法 |
URL映射 |
`@ResponseBody |
类/方法 |
以Json方式返回 |
`@RequestParam |
参数 |
按名字接收参数 |
`@RequestBody |
参数 |
接收Json参数 |
`@PathVariable |
参数 |
接收URL中的参数 |
2) 组合注解
-
@RestController
= @Controller
+ @ResponseBody
-
@GetMapping
= @RequestMapping(method = RequestMethod.GET)
-
@PostMapping
= @RequestMapping(method = RequestMethod.POST)
-
@PutMapping
= @RequestMapping(method = RequestMethod.PUT)
-
@PatchMapping
= @RequestMapping(method = RequestMethod.PATCH)
-
@DeleteMapping
= @RequestMapping(method = RequestMethod.DELETE)
3) 接收参数
- @RequestParam 属性
- name: String 参数名称,默认取后续定义的变量名称
- value: String name属性别名
- required: boolean 是否必传
- defaultValue: String 参数默认值
@ApiOperation("Hello Spring Boot 方法")
@GetMapping("/")
public String hello(@RequestParam(required = false) @ApiParam("名字")
String name) {
if (!StringUtils.isEmpty(name)) {
return String.format("Hello %s", name);
}
return "Hello Spring Boot";
}
- @PathVariable方式
- name: String 参数名称,默认取后续参数定义的名称
- value: String name属性别名
- required: boolean 制是否必传
@ApiOperation(value = "@PathVariable方式")
@GetMapping("/pathvariable/{name}/{age}")
public User PathVariable(@PathVariable String name,@PathVariable int age) {
...
return user;
}
- @RequestBody方式
@ApiOperation(value = "@RequestBody方式")
@PostMapping("/requestbody")
public User RequestBody(@RequestBody User user) {
return user;
}
网友评论