第一步:在属性上面加 @size()注解
import lombok.Data;
import lombok.NonNull;
import javax.validation.constraints.Size;
@Data
public class ModifyBean {
// 备注信息
@NonNull
private String remark;
// 规则id
@NonNull
private Integer ruleId;
// 规则配置json
private String configJson;
//规则名称
@NonNull
@Size(max = 30, message = "xx名称长度不能超过30")
private String ruleName;
}
第二步: @Validated 注解
@PostMapping(value = "/moxx")
@ApiOperation(value = "编辑xx", notes = "")
public Map<String, Object> modifyRule(@RequestBody @Validated ModifyBean bean,
HttpServletRequest request) {
第三步: 对抛出的异常进行进一步处理,否则会抛出一大堆异常栈信息。
在Spring 全局异常处理类中处理异常
@ControllerAdvice
public class GlobalExceptionHandler extends BaseController
@ResponseBody
@ExceptionHandler(MethodArgumentNotValidException.class)
public Map<String, Object> globalException(MethodArgumentNotValidException e, HttpServletRequest request) {
BindingResult bindingResult = e.getBindingResult();
String erroeMsg = "";
List<FieldError> fieldErrors = bindingResult.getFieldErrors();
for (FieldError fieldError : fieldErrors) {
erroeMsg += fieldError.getDefaultMessage();
}
return failedResult(null, "参数校验不通过", erroeMsg, request, null, "Exception", e.getMessage(), null);