首页 > 其他分享 >springboot web 自定义参数验证

springboot web 自定义参数验证

时间:2022-11-03 17:24:39浏览次数:52  
标签:username web AjaxResult return springboot 自定义 class user public

当需要前端必传某些参数的时候,可在代码里面校验,但是这样每一个方法都需要自己写代码验证。我们可以使用spring提供的@Validate

1、单一参数验证

  接口是单一参数写在方法上时:

  @GetMapping("/user")
    public AjaxResult<User> getUser(@RequestParam String username){
        System.err.println("username:"+username);
        User user = userService.findByUsername(username);
        return AjaxResult.success(user);
    }

  username 是要求必传的,直接请求接口,不传username参数,服务端会报错

  

 

 

   但是,传空字符串时,就会通过验证:

  

  在类上加@Validate,参数加@NotBlank验证:

@RestControllerAdvice
@RestController
@Validated
@RequestMapping("/users")
public class UserController {
    @Resource
    private IUserService userService;

    @GetMapping("/user")
    public AjaxResult<User> getUser(@NotBlank(message = "用户名不能为空") @RequestParam String username){
        System.err.println("username:"+username);
        User user = userService.findByUsername(username);
        return AjaxResult.success(user);
    }
}

  配合全局异常处理:

@RestControllerAdvice
public class CommonExceptionHandler {
    @ExceptionHandler(value = {ConstraintViolationException.class})
    public AjaxResult<?> exceptionHandler(ConstraintViolationException e){
        return AjaxResult.fail(e.getMessage());
    }

    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    public AjaxResult<?> exceptionHandler(MethodArgumentNotValidException e){
        return AjaxResult.fail(e.getBindingResult().getFieldError().getDefaultMessage());
    }

}

 

2、多个参数验证

@Data
public class UserEditRequest implements Serializable {
    @NotBlank(message = "username不能为空")
    private String username;
    @NotBlank(message = "密码不能为空")
    private String password;
}

@PutMapping
public AjaxResult<Boolean> save(@Validated @RequestBody UserEditRequest request){
System.err.println(request);
return AjaxResult.success(true);
}
 

 

标签:username,web,AjaxResult,return,springboot,自定义,class,user,public
From: https://www.cnblogs.com/junnnnnnnn/p/16855159.html

相关文章