面试题答案
一键面试- 使用@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"; } }
- 自定义错误信息
- 如上述示例,在验证注解中通过
message
属性自定义错误信息。例如@NotBlank(message = "用户名不能为空")
,这样当验证失败时,就会返回自定义的错误提示。
- 如上述示例,在验证注解中通过
- 全局层面统一处理验证异常
- 创建一个全局异常处理器。
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
。