1) springMVC常用注解
注解 |
作用域 |
說明 |
`@Controller |
類 |
Controller標(biāo)識 |
`@RequestMapping |
類/方法 |
URL映射 |
`@ResponseBody |
類/方法 |
以Json方式返回 |
`@RequestParam |
參數(shù) |
按名字接收參數(shù) |
`@RequestBody |
參數(shù) |
接收J(rèn)son參數(shù) |
`@PathVariable |
參數(shù) |
接收URL中的參數(shù) |
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) 接收參數(shù)
- @RequestParam 屬性
- name: String 參數(shù)名稱,默認(rèn)取后續(xù)定義的變量名稱
- value: String name屬性別名
- required: boolean 是否必傳
- defaultValue: String 參數(shù)默認(rèn)值
@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 參數(shù)名稱,默認(rèn)取后續(xù)參數(shù)定義的名稱
- 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;
}