在后端开发的过程中,验证前端参数的合法性是一个必不可少的步骤
一、依赖
<!--web启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--thymeleaf启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
二 实体类
package com.example.demo.entity; import sun.plugin2.message.Message; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; public class User { public Integer ID; public Integer getID() { return ID; } public void setID(int ID) { this.ID = ID; } //不填写 message 就显示默认值 @NotBlank(message ="用户不能为空") public String UserName; @NotBlank(message="用户密码不能为空") public String Pwd; public String Age; public String getUserName() { return UserName; } public User(Integer ID, String userName, String pwd, String age) { this.ID = ID; UserName = userName; Pwd = pwd; Age = age; } public void setUserName(String userName) { UserName = userName; } public String getPwd() { return Pwd; } public void setPwd(String pwd) { Pwd = pwd; } public String getAge() { return Age; } public void setAge(String age) { Age = age; } } 三 控制器Controller
package com.example.demo.Controller; import com.example.demo.entity.User; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import javax.validation.Valid; @Controller public class UserController { /* 如果想更改对象可以用 @ModelAttribute("aa") ,这表示当前传递的对象Key也要修改 默认可以不用 @ModelAttribute("aa") */ @RequestMapping("/ShowPage") public String ShowPage(@ModelAttribute("aa") User user) { return "AddUserInfo"; } /* 添加用户 @Valid 开启对User对象的数据校验 BindingResult 封装了校验的结果 */ @RequestMapping("/Add") public String Save(@ModelAttribute("aa") @Valid User user, BindingResult result) { if(result.hasErrors()) { return "AddUserInfo"; } return "OK"; } } 四 页面显示 @ModelAttribute("aa") 与 th:errors="${aa.UserName} 要一至
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>添加用户</title> </head> <body> <form th:action="@{/Add}" method="post"> <input type="hidden" name="ID"> 用户名<input type="input" name="UserName"><font color="red" th:errors="${aa.UserName}"> </font><br/> 用户密码<input type="input" name="Pwd"><font color="red" th:errors="${aa.Pwd}"> </font><br/> 用户性别<input type="input" name="Age"><br/> <input type="submit" value="确定" /> </form> </body> </html>
五 结果