springBoot獲取@NotBlank,@NotNull注解的message信息


概述

  springBoot后台驗證接收的參數是否不合法時,會拋出一個BlndException異常,獲取message的自定義信息並返回

驗證

UserEntity類

@Data
@Entity
@Table(name = "t_user")
@ApiModel
public class UserEntity
{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @NotBlank(message = "username不能為空")
    @Column(name = "name")
    private String username;

    @NotBlank(message = "password不能為空")
    private String password;
}

 統一異常處理

@ResponseBody
    @ExceptionHandler(BindException.class)
    public ResponseJsonResult exceptionHandler(BindException e)
    {
        e.printStackTrace();
        ResponseJsonResult responseJsonResult = new ResponseJsonResult();
        responseJsonResult.setState(Constant.ERROR);
        responseJsonResult.setErrorCode(ExceptionCode.IV00007);
        responseJsonResult.setMessage(e.getBindingResult().getFieldError().getDefaultMessage());
        return responseJsonResult;
    }
e.getBindingResult().getFieldError().getDefaultMessage()就是獲取默認的異常信息

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM