使用Hibernate Validator验证表单信息,具体要求入下:
(1)用户名必须输入,并且长度范围为5~20
(2)年龄范围在18~60
(3)工作日期在系统日期之前
1-创建Maven项目,并在pom.xml文件中中添加相关依赖。
4.0.0 org.example Thymeleaf 1.0-SNAPSHOT org.springframework.boot spring-boot-starter-parent 2.1.4.RELEASE org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-thymeleaf
2-在src/main/java目录下创建com.model包,在该包中创建实体模型类,并在该类中进行注解验证。
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.Range;
import org.springframework.format.annotation.DateTimeFormat;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Past;
import java.util.Date;
public class People {
@NotBlank(message = "用户名必须输入")
@Length(min = 5, max = 20, message = "用户名长度范围在5~20之间 ")
private String username ;
@Range(min = 18, max = 60, message = "年龄范围在18~60之间")
private int age ;
@Past(message = "当前日期必须在系统日期之前")
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date date ;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
3-在src/main/java目录下创建com.controller包,在该包中创建控制器类,在控制器类中有两个方法,一个初始化方法,一个添加请求处理方法。
import com.model.People;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class TestValidator {
@RequestMapping("/test")
public String test(@ModelAttribute("peopleInfo")People people){ //初始化页面方法
return "test" ;
}
@RequestMapping("/addUser")
public String add(@ModelAttribute("peopleInfo") @Validated People people, BindingResult result){
if(result.hasErrors()){
return "test" ; //验证失败
}
return "test1" ; //验证成功,跳到test1.html页面
}
}
4-在src/main/resources/templates目录下创建视图页面test.html
表单验证页面
数据验证
添加用户
5-在src/main/java目录下创建包com.test,在该包中创建启动类,运行启动类。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(scanbasePackages = {"com"})
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args) ;
}
}
访问http://localhost:8080/test地址,并输入错误信息,点击添加,如下图所示:



