勾选web,thymeleaf,lombok
pom.xml添加
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-el</artifactId>
</dependency>
PersonForm
@Getter
@Setter
@ToString
public class PersonForm {
@NotNull
@Size(min=2,max = 30)
private String name;
@NotNull
@Min(18)
private Integer age;
}
WebController
@Controller
public class WebController extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/results").setViewName("results");
}
@GetMapping("/")
public String showForm(PersonForm personForm){
return "form";
}
@PostMapping("/")
public String checkPersonInfo(@Valid PersonForm personForm, BindingResult bindingResult){
if (bindingResult.hasErrors()){
return "form";
}
return "redirect:/results";
}
}
form.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8"/>
<title>登录注册</title>
</head>
<body>
<form action="#" th:action="@{/}" th:object="${personForm}" method="post">
<table>
<tr>
<td>姓名:</td>
<td><input type="text" th:field="*{name}"/></td>
<td th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Name Error</td>
</tr>
<tr>
<td>年龄:</td>
<td><input type="text" th:field="*{age}"/></td>
<td th:if="${#fields.hasErrors('age')}" th:error="*{age}">未满18岁禁止入内</td>
</tr>
<tr>
<td><button type="submit">提交</button> </td>
</tr>
</table>
</form>
</body>
</html>
result.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>results</title>
</head>
<body>
本网站成人内容收集于全世界的互联网,网站在美国进行维护,受美国法律保护
</body>
</html>
鸣谢:http://blog.youkuaiyun.com/forezp/article/details/71023817