步骤
- 建项目,包含三项 web, thymeleaf, validation
- 建一个实体类,写好校验注解
- 建一个控制器,写好方法,并在接收数据的方法上写好校验用的注解
- 建一个表单页面
1.建项目
我在 https://start.spring.io/ 新建项目
2.写实体类
把下载好的项目解压,开始添加java文件
第一个文件:UserForm.java
package com.example.entity;
import lombok.Data;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
@Data
public class UserForm {
private Long id;
@NotEmpty(message = "用户名不能为空")
@Length(min = 2, max = 32, message = "用户名长度在2到32个字符之间")
private String username;
@NotEmpty(message = "密码不能为空")
@Length(min = 6, max = 32, message = "密码长度在6到32个字符之间")
private String password;
}
第二个文件:IndexController.java
package com.example.controller;
import com.example.entity.UserForm;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class IndexController {
@RequestMapping("/index")
public String index(@ModelAttribute("userInfo") UserForm user) {
//设定model值
user.setPassword("test_ps");
user.setUsername("test");
return "admin/index";
}
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String add(@ModelAttribute("userInfo") @Validated UserForm user, BindingResult rs) {
System.out.println(rs);
if (rs.hasErrors()) {
for (ObjectError error : rs.getAllErrors()) {
System.out.println(error.getDefaultMessage());
}
}
return "admin/index";
}
}
第三个文件:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title th:text="${username}">xx</title>
</head>
<body>
<h1 th:text="${username}">Hello World</h1>
<h1>获取对象信息</h1>
<h2>1、通过直接访问对象的方式</h2>
<p th:text="${userInfo.username}"></p>
<p th:text="${userInfo.password}"></p>
<h2>2、通过th:object访问对象的方式</h2>
<div th:object="${userInfo}">
<p th:text="*{username}"></p>
<p th:text="*{password}"></p>
</div>
<h1>表单提交</h1>
<!-- 表单提交用户信息,注意字段的设置,直接是*{} -->
<form action="#" th:action="@{/add}" th:object="${userInfo}" method="post">
<div><span>用户名</span><input type="text" th:field="*{username}" /> <span th:if="${#fields.hasErrors('username')}" th:errors="*{username}"></span></div>
<div><span>密码</span><input type="text" th:field="*{password}" /> <span th:if="${#fields.hasErrors('password')}" th:errors="*{password}"></span></div>
<input type="submit" />
</form>
</body>
</html>
原文章参考:https://blog.csdn.net/yelllowcong/article/details/79831023