SpringBoot的参数注解

2019-04-11  本文已影响0人  CoderLJW
1、@PathVariable:接收请求路径中占位符的值
URL:http://localhost:9010/aa/789/mm/333
// 代码
    @RequestMapping("aa/{user}/mm/{num}")
    @ResponseBody
    public RestResponse activityaa(@PathVariable("user") String userID, @PathVariable("num") String num){
        return RestResponse.success(userID + "----" + num);
    }
// 返回
{"code":0,"msg":"OK","count":0,"data":"789----333"}
@RequestMapping("/aa/{user:[a-zA-Z0-9_]+}/mm/{num}")
2、@RequestParam:用于绑定请求参数里面的值
URL: http://localhost:9010/aa?uu=22&user=44&num=55
// 代码
    @RequestMapping("aa")
    @ResponseBody
    public RestResponse activityaa11(@RequestParam String uu, @RequestParam("user") String userID, @RequestParam("num") String num){
        return RestResponse.success(uu + "----" + userID + "----" + num);
    }
// 结果
{"code":0,"msg":"OK","count":0,"data":"22----44----55"}
@RequestParam(name="num",required=false,defaultValue="0")
URL:  http://localhost:9010/bb?uu=22&userID=44
// 代码
    @RequestMapping("bb")
    @ResponseBody
    public RestResponse activityaa22(String uu, String userID, String num){
        return RestResponse.success(uu + "----" + userID + "----" + num);
    }
// 返回
{"code":0,"msg":"OK","count":0,"data":"22----44----null"}
3、@RequestBody:注解接受参数是来自于body内容中,请求格式必须是raw并且是application/json
@PostMapping(value = "/11")
    public RestResponse device11(
            @RequestBody Test test
    ){
        if (StringUtils.isEmpty(test.getName())
                || test.getAdd() == null){
            return RestResponse.error(RestCode.ParamsAndInstanceIsNull);
        }
        return RestResponse.success(deviceService.deviceList());
    }
image.png
4、如果是下面这个情况
@PostMapping(value = "/11")
public RestResponse device11(Test test){}
5、校验

javax.validation.constraints里面自带的像@NotNull @NotEmpty...等等这类注解

- 定义类
@Data
public class Test22 {

    @NotNull
    @NotEmpty
    private String name;
    private Integer add;
}
- 使用类
public RestResponse device11(@Valid Test11 test11){}
- 无效
public RestResponse device11(@NotNull String name){}

- 有效 用到另外一个注解 import lombok.NonNull;
public RestResponse device11(@NonNull String name){}

lombok.NonNull 这类的lombok下的注解,可以用在属性、参数等。直接使用,直接生效

上一篇下一篇

猜你喜欢

热点阅读