SpringBoot学习笔记第四天--数据校验注释的使用

这是学习spring boot的 第四天了,为什么之前两天的没写呢 ,因为实在是太简单了,就懒得写,

可我又有一些处女座的强迫症情节,所以有时间的话还是补上的。

今天学习主要的心得:

                            spring boot的数据校验

 

还是老话 :                       愿你我共同成长 ! ! !。。。。

 

代码来了。。。。。

 

前提创建Users类(这是属性 )


	private String name;
	private Integer age;
	private String passWorld;

1.创建一个新项目 :

          具体参考第一天,唯一的不同就是在pom.xml文件中添加
 

<!-- thymeleaf启动器 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>

2.写一个控制类(实现功能就是添加用户,这个很简单,不要求写dao层)

@RequestMapping("/addUser")
	public String addUser() {
		return "add";
	}

@RequestMapping("/save")
	public String saveUser( Users users) {
		return "ok";
	}

3.写html页面(add.html和ok.html)(注意,和你的实体类名称对应哈)

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>添加用户</title>
</head>
<body>
	<form th:action="@{/users/save}" method="post">
		用户姓名:<input type="text" name="name" /><font color="red"
			th:errors="${users.name}"></font><br /> 
		用户密码:<input type="passWorld"
			name="passWorld" /><font color="red" th:errors="${users.passWorld}"></font><br />
		用户年龄:<input type="text" name="age" /><font color="red"
			th:errors="${users.age}"></font><br /> 
			<input type="submit" value="OK" />
	</form>
</body>
</html>





<--!这是ok.html的内容别看错了-->



<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>操作提示页面</title>
</head>
<body>
操作成功!!!
</body>
</html>

4.现在创建一个启动类,启动,具体怎么做我就不用说了吧。

是不是报错了?

org.thymeleaf.exceptions.TemplateProcessingException: Error during execution of processor 'org.thymeleaf.spring4.processor.SpringErrorsTagProcessor' (template: "add" - line 10, col 4)

让我来告诉你怎么解决。

   在跳转页面的方法中注入一个对象,来解决问题。要求参数对象的变量名必须是对象的类名的全称首字母小写。

 

现在开始校验的注释部分

@Valid 校验对象的数据(对你传过来的数据进行校验)
 BindingResult 封装了异常信息 异常校验

/**
	 * 用户添加
	 * 
	 * @Valid 校验对象的数据
	 *  BindingResult 封装了异常信息 异常校验
	 *
	 */
	@RequestMapping("/save")
	public String saveUser(@Valid Users users, BindingResult result) {
               return "ok";
	}

这是pojo层实体类的一些非空校验

@NotBlank   这是非空校验(和@NotEmpty区别就是去除头尾的空格)


	@NotBlank
	private String name;
	private Integer age;
	@NotBlank
	private String passWorld;



在controller中加一个判断

看效果(按照要求,不填写的时候就会出现这个,哈哈哈)

 

还有很多校验,需要的话直接填写在你的pojo上,我都是试了试,不错,真不错。

@NotEmpty: 判断字符串是否 null 或者是空串。
@Length: 判断字符的长度(最大或者最小)
@Min: 判断数值最小值
@Max: 判断数值最大值
@Email: 判断邮箱是否合法

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值