MST
星途 面试题库

面试题:Java微服务架构下Spring Boot如何实现数据验证

在Java的Spring Boot微服务项目中,通常需要对用户输入的数据进行验证。请描述如何利用Spring Boot内置的验证机制,比如使用@Valid注解等,来实现对请求参数的数据验证,并处理验证失败的情况,包括如何自定义错误信息以及在全局层面统一处理验证异常。
17.9万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试
  1. 使用@Valid注解进行数据验证
    • 首先,定义一个Java Bean来表示请求参数,在该Bean的属性上添加验证注解。例如:
    import javax.validation.constraints.NotBlank;
    public class UserRequest {
        @NotBlank(message = "用户名不能为空")
        private String username;
        @NotBlank(message = "密码不能为空")
        private String password;
        // 省略getter和setter方法
    }
    
    • 在Controller方法中,对传入的参数使用@Valid注解进行验证。
    import org.springframework.validation.annotation.Validated;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RestController;
    @RestController
    @Validated
    public class UserController {
        @PostMapping("/users")
        public String createUser(@Valid @RequestBody UserRequest userRequest) {
            // 业务逻辑,当验证通过才会执行到这里
            return "User created successfully";
        }
    }
    
  2. 自定义错误信息
    • 如上述示例,在验证注解中通过message属性自定义错误信息。例如@NotBlank(message = "用户名不能为空"),这样当验证失败时,就会返回自定义的错误提示。
  3. 全局层面统一处理验证异常
    • 创建一个全局异常处理器。
    import org.springframework.http.HttpStatus;
    import org.springframework.http.ResponseEntity;
    import org.springframework.validation.FieldError;
    import org.springframework.web.bind.MethodArgumentNotValidException;
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import java.util.HashMap;
    import java.util.Map;
    @ControllerAdvice
    public class GlobalExceptionHandler {
        @ExceptionHandler(MethodArgumentNotValidException.class)
        public ResponseEntity<Map<String, String>> handleValidationExceptions(
                MethodArgumentNotValidException ex) {
            Map<String, String> errors = new HashMap<>();
            ex.getBindingResult().getAllErrors().forEach((error) -> {
                String fieldName = ((FieldError) error).getField();
                String errorMessage = error.getDefaultMessage();
                errors.put(fieldName, errorMessage);
            });
            return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
        }
    }
    
    • 上述代码中,@ControllerAdvice注解表示这是一个全局异常处理器,@ExceptionHandler(MethodArgumentNotValidException.class)处理方法参数验证失败的异常。在处理方法中,将错误信息提取并封装到Map中,返回给客户端带有错误信息的响应,状态码为400 Bad Request