这是学习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: 判断邮箱是否合法