1、导入依赖。(springmvc的stater-web和json依赖也需要添加,此处先不列举)
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-validation</artifactId></dependency>
2、使用示例:
(1)接收客户端参数实体类dto
package com.example.dto;import com.example.pojo.SysJob;
import lombok.Data;import javax.validation.constraints.NotBlank;@Data
public class SysJobDto {@NotBlank(message = "不能为空")private String pageNum;private String pageSize;private SysJob sysJob;
}
(2)controller添加@Valid触发验证
@PostMapping("/getJob")public ResponseEntity<String> getJob(@Valid @RequestBody SysJobDto sysJobDto){return new ResponseEntity<>("User is valid", HttpStatus.OK);//return iSysJobService.getJobList(sysJobDto.getSysJob(),sysJobDto.getPageNum(),sysJobDto.getPageSize());}
(3)这里还有一个问题需要解决(校验错误,这里没办法自动把@notBlank的message传递给前端。需要添加一个全局异常处理器,将错误信息返回给前端)
解决方式:添加两个类。
全局异常处理器类:GlobalExceptionHandler.java
返回的异常信息实体类:ErrorResponse.java
GlobalExceptionHandler.java
package com.example.utils;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 org.springframework.web.bind.annotation.ResponseStatus;import java.util.HashMap;
import java.util.Map;@ControllerAdvice
public class GlobalExceptionHandler {@ExceptionHandler(MethodArgumentNotValidException.class)@ResponseStatus(HttpStatus.BAD_REQUEST)public ResponseEntity<ErrorResponse> 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);});ErrorResponse errorResponse = new ErrorResponse(HttpStatus.BAD_REQUEST.value(),"Validation failed",System.currentTimeMillis(),errors);return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);}
}
ErrorResponse.java
package com.example.utils;import lombok.Data;import java.util.Map;
@Data
public class ErrorResponse {private int status;private String message;private long timestamp;private Map<String, String> errors;public ErrorResponse(int status, String message, long timestamp, Map<String, String> errors) {this.status = status;this.message = message;this.timestamp = timestamp;this.errors = errors;}// getters and setters
}