11. SpringMVC-常用注解

1) springMVC常用注解

注解 作用域 说明
`@Controller Controller标识
`@RequestMapping 类/方法 URL映射
`@ResponseBody 类/方法 以Json方式返回
`@RequestParam 参数 按名字接收参数
`@RequestBody 参数 接收Json参数
`@PathVariable 参数 接收URL中的参数

2) 组合注解

  1. @RestController = @Controller + @ResponseBody
  2. @GetMapping = @RequestMapping(method = RequestMethod.GET)
  3. @PostMapping = @RequestMapping(method = RequestMethod.POST)
  4. @PutMapping = @RequestMapping(method = RequestMethod.PUT)
  5. @PatchMapping = @RequestMapping(method = RequestMethod.PATCH)
  6. @DeleteMapping = @RequestMapping(method = RequestMethod.DELETE)

3) 接收参数

  1. @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";
    }
  1. @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;
}
  1. @RequestBody方式
    • required: boolean 是否必传
@ApiOperation(value = "@RequestBody方式")
@PostMapping("/requestbody")
public User RequestBody(@RequestBody User user) {
    return user;
}

你可能感兴趣的:(11. SpringMVC-常用注解)