这个例子用于演示在Spring Boot应用中如何验证Web 应用的输入,我们将会建立一个简单的Spring MVC应用,来读取用户输入并使用validation注解来检查,并且当用户输入错误时,应用需要再屏幕上显示错误信息提示用户重新输入。
首先构建Maven项目,该项目的pom文件内容如下:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>validating-form-input</artifactId> <version>1.0-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.1.RELEASE</version> </parent> <properties> <java.version>1.8</java.version> </properties> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> <dependencies> <!-- thymeleaf模板,用于前段渲染 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!-- 用于输入验证 --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> </dependency> <!-- 用于支持嵌入式tomcat --> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-el</artifactId> </dependency> <!-- 用于spring boot应用的测试 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> </project>
Spring Boot Maven插件提供了很多方便的特性:
它将该项目中需要的各个Jar包收集起来,并打包成可直接运行的Jar包,以更方便得部署和传输; 它会搜索包含“public static void main()”方法的类,该类就是可运行Jar包的启动类; 它提供了内在的支持,去匹配Spring Boot的版本号。Form对象
创建一个Form对象,用于对应HTML页面中输入的对象——PersonForm,
package hello; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * Created by IntelliJ IDEA. * User: duqi * Date: 2017/2/28 * Time: 21:53 */ public class PersonForm { @NotNull @Size(min = 2, max = 30) private String name; @NotNull @Min(18) private Integer age; public String getName() { return name; } public Integer getAge() { return age; } public void setName(String name) { this.name = name; } public void setAge(Integer age) { this.age = age; } public String toString() { return "Person(Name: " + this.name + ", Age: " + this.age + ")"; } }