spring 注解验证@NotNull等使用方法

点击链接加入群聊【java菜鸟学习】:https://jq.qq.com/?_wv=1027&k=5afU7nS
群号:124569404
常用标签

@Null  被注释的元素必须为null
@NotNull  被注释的元素不能为null
@AssertTrue  被注释的元素必须为true
@AssertFalse  被注释的元素必须为false
@Min(value)  被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@Max(value)  被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@DecimalMin(value)  被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@DecimalMax(value)  被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@Size(max,min)  被注释的元素的大小必须在指定的范围内。
@Digits(integer,fraction)  被注释的元素必须是一个数字,其值必须在可接受的范围内
@Past  被注释的元素必须是一个过去的日期
@Future  被注释的元素必须是一个将来的日期
@Pattern(value) 被注释的元素必须符合指定的正则表达式。
@Email 被注释的元素必须是电子邮件地址
@Length 被注释的字符串的大小必须在指定的范围内
@NotEmpty  被注释的字符串必须非空
@Range  被注释的元素必须在合适的范围内

example :
vo 页面传过来的数据进行校验
inferface : 只是作为标记一个组别 可以在vo验证的某个字段上面加入多个组别,这样没有加入的组别就不会验证这个字段
controller: 需要 加入 @Validated (GroupInterface1.class) //GroupInterface1.class是定义的分组 GroupInterface2.class 需要校验的字段是不会验证的

VO:

public class User implements Serializable {
    /**
     * 主键
     */
    @NotNull(message = "primary is not null",groups = {GroupInterface1.class})
	private Long id;
	
	@Pattern(regexp = "[0123456789]",groups = {GroupInterface1.class,GroupInterface2.class},message = "hava a error Date")
	private Long maxDiscountAmount;
	

	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
	private Date createTime;

	@Future(message = "expireTime is not less than now",groups = {GroupInterface1.class,GroupInterface2.class})
	@NotNull(message = "expireTime is not null",groups = {GroupInterface1.class,GroupInterface2.class})
	private Date expireTime;

}

另外一个例子:

import java.util.Date;

import javax.validation.constraints.DecimalMax;
import javax.validation.constraints.DecimalMin;
import javax.validation.constraints.Email;
import javax.validation.constraints.Future;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.Range;
import org.springframework.format.annotation.DateTimeFormat;

/**** imports ****/
public class ValidatorPojo {

	// 非空判断
	@NotNull(message = "id不能为空")
	private Long id;

	@Future(message = "需要一个将来日期") // 只能是将来的日期
	// @Past //只能去过去的日期
	@DateTimeFormat(pattern = "yyyy-MM-dd") // 日期格式化转换
	@NotNull // 不能为空
	private Date date;

	@NotNull // 不能为空
	@DecimalMin(value = "0.1") // 最小值0.1元
	@DecimalMax(value = "10000.00") // 最大值10000元
	private Double doubleValue = null;

	@Min(value = 1, message = "最小值为1") // 最小值为1
	@Max(value = 88, message = "最大值为88") // 最大值88
	@NotNull // 不能为空
	private Integer integer;

	@Range(min = 1, max = 888, message = "范围为1至888") // 限定范围
	private Long range;

	// 邮箱验证
	@Email(message = "邮箱格式错误")
	private String email;

	@Size(min = 20, max = 30, message = "字符串长度要求20到30之间。")
	private String size;

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

	public Double getDoubleValue() {
		return doubleValue;
	}

	public void setDoubleValue(Double doubleValue) {
		this.doubleValue = doubleValue;
	}

	public Integer getInteger() {
		return integer;
	}

	public void setInteger(Integer integer) {
		this.integer = integer;
	}

	public Long getRange() {
		return range;
	}

	public void setRange(Long range) {
		this.range = range;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getSize() {
		return size;
	}

	public void setSize(String size) {
		this.size = size;
	}

	/**** setter and getter ****/

}

此时controller应该要加上@Valid ,否则不会验证!

	/***
	 * 解析验证参数错误
	 * @param vp —— 需要验证的POJO,使用注解@Valid 表示验证
	 * @param errors  错误信息,它由Spring MVC通过验证POJO后自动填充
	 * @return 错误信息Map
	 */
	@RequestMapping(value = "/valid/validate")
	@ResponseBody
	public Map<String, Object> validate(
	        @Valid @RequestBody ValidatorPojo vp, Errors errors) {
	    Map<String, Object> errMap = new HashMap<>();
	    // 获取错误列表
	    List<ObjectError> oes = errors.getAllErrors();
	    for (ObjectError oe : oes) {
	        String key = null;
	        String msg = null;
	        // 字段错误
	        if (oe instanceof FieldError) {
	            FieldError fe = (FieldError) oe;
	            key = fe.getField();// 获取错误验证字段名
	        } else {
	            // 非字段错误
	            key = oe.getObjectName();// 获取验证对象名称
	        }
	        // 错误信息
	        msg = oe.getDefaultMessage();
	        errMap.put(key, msg);
	    }
	    return errMap;
	}

GROUP interface(分组)

  • 56
    点赞
  • 280
    收藏
    觉得还不错? 一键收藏
  • 17
    评论
Spring MVC中的@NotNull注解是用于验证请求参数或方法参数是否为null的注解。在使用@NotNull注解时,需要先引入相关的依赖。根据引用和引用所提供的信息,可以使用以下依赖解决这个问题: ```xml <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>2.0.1.Final</version> </dependency> <dependency> <groupId>org.hibernate.validator</groupId> <artifactId>hibernate-validator</artifactId> <version>6.0.7.Final</version> </dependency> ``` 在Spring MVC中使用@NotNull注解时,需要在参数上添加该注解以进行验证。例如: ```java @RequestMapping("/example") public void exampleMethod(@NotNull String parameter) { // method implementation } ``` 这样,在请求参数"parameter"为null时,会抛出验证异常。通过使用@NotNull注解,可以有效地验证参数的有效性。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [SpringMVC @NotNull校验不生效](https://blog.csdn.net/YKRY35/article/details/100778402)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [Java和springmvc@NotNull报错,校验不生效!](https://blog.csdn.net/Mrs_chens/article/details/102664415)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [基于mysql+ssm+bootstrap的员工管理系统项目源码](https://download.csdn.net/download/qq_35831906/88227142)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 17
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值