Springboot验证表单数据和自定义验证
程序员文章站
2022-05-03 10:23:53
...
验证表单
实验结果
项目结构目录如下
0.添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
0.设置路径
application.properties文件
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.servlet.content-type=text/html
spring.thymeleaf.encoding=utf-8
spring.thymeleaf.mode=LEGACYHTML5
spring.thymeleaf.cache=false
spring.mvc.static-path-pattern=/**
spring.resources.static-locations=classpath:/static/
1.创建实体
User.java
package com.example.demo.entity;
import lombok.Data;
import org.hibernate.validator.constraints.Length;
//import hibernate.validator.constraints.Length;
import javax.validation.constraints.*;
import java.io.Serializable;
@Data
public class User implements Serializable {
/**
* 主键:id
* */
private Long id;
@NotBlank(message = "用户名不能为空")
@Length(min=5,max=20,message = "用户名长度为5-20个字符")
private String name;
@NotNull(message = "年龄不能为空")
@Min(value=18,message = "最小18岁")
@Max(value=60,message = "最大60岁")
private Integer age;
@Email(message = "请输入邮箱")
@NotBlank(message = "邮箱不能为空")
private String email;
}
2.编写验证控制器
用于绑定数据验证
TestValidator.java
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.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.validation.Valid;
@Controller
public class TestValidator {
@GetMapping("/test")
public String showForm(User user){
return "form";
}
@GetMapping("/results")
public String results(){
return "results";
}
@PostMapping("/test")
public String checkUser(@Valid User user,BindingResult bindingResult,RedirectAttributes attr){
if(bindingResult.hasErrors()){
return "form";
}
attr.addFlashAttribute("user",user);
return "redirect:/results";
}
}
3.编写视图
form.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<style type="text/css">
.warn{color:red}
</style>
<form th:action="@{/test}" th:object="${user}" method="post">
<div>
<div>
<span>姓名:</span>
<span><input type="text" th:field="*{name}"/></span>
<span class="warn" th:if="${#fields.hasErrors('name')}" th:errors="*{name}">名字错误</span>
</div>
<div>
<span>年龄:</span>
<span><input type="number" th:field="*{age}"/></span>
<span class="warn" th:if="${#fields.hasErrors('age')}" th:errors="*{age}">年龄错误</span>
</div>
<div>
<span>邮箱:</span>
<span><input TYPE="text" th:field="*{email}"/></span>
<span class="warn" th:if="${#fields.hasErrors('email')}" th:errors="*{email}">邮箱错误</span>
</div>
<div>
<span>
<button type="submit">提交</button>
</span>
</div>
</div>
</form>
</body>
</html>
results.html
如果验证成功,使用本视图进行渲染数据;如果验证失败,返回表单提示错误
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<div th:each="user:${user}">
恭喜您,<span th:text="${user.name}">名字</span>(先生/女士),数据提交成功!
<div>
您的年龄是:
<span th:text="${user.age}"></span>
</div>
<div>
您的邮箱是:
<span th:text="${user.email}"></span>
</div>
</div>
</body>
</html>
4.运行项目
打开http://localhost:8080/test
自定义验证
实验结果
项目结构
application.properties文件
spring.thymeleaf.mode=HTML
spring.thymeleaf.cache=false
1.自定义注解类
MyConstraintValdator.java
package com.example;
import com.example.demo.MyConstraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class MyConstraintValdator implements ConstraintValidator<MyConstraint, String> {
//String为校验的类型
@Override
public void initialize(MyConstraint myConstraint) {
//启动时执行
}
/**
* @ Description: 自定义校验逻辑
*/
@Override
public boolean isValid(String s, ConstraintValidatorContext validatorContext) {
if (!(s.equals("北京") || s.equals("上海"))) {
return false;
}
return true;
}
}
2.自定义验证业务逻辑类
有两个方法:initialize和isValid
MyConstraint .java
package com.example.demo;
import com.example.MyConstraintValdator;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
//限定使用范围:只能在字段上使用
@Target({ElementType.FIELD})
//表明注解的生命周期,它在代码运行时可以通过反射获取到注解
@Retention(RetentionPolicy.RUNTIME)
//@Constraint 注解,里面传入一个validateBy字段,以指定该注解的校验逻辑
@Constraint(validatedBy= MyConstraintValdator.class)
public @interface MyConstraint {
/**
* @ Description:错误提示
* */
String message() default "请输入*中心或经济中心的城市名";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
3.创建实体
User.java
package com.example.demo.entity;
import com.example.demo.MyConstraint;
import lombok.Data;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.*;
import java.io.Serializable;
@Data
public class User implements Serializable {
/**
* 主键ID
*/
private Long id;
@NotBlank(message = "用户名不能为空")
@Length(min = 5, max = 20, message = "用户名长度为5-20个字符")
private String name;
@NotNull(message = "年龄不能为空")
@Min(value = 18 ,message = "最小18岁")
@Max(value = 60,message = "最大60岁")
private Integer age;
/* @NotBlank(message = "电话不可以为空")
@Length(min = 1, max = 13, message = "电话长度需要在13个字符以内")
private String phone;*/
@Email(message = "请输入邮箱")
@NotBlank(message = "邮箱不能为空")
private String email;
/* @NotNull(message = "必须指定用户状态")
@Min(value = 0, message = "用户状态不合法")
@Max(value = 1, message = "用户状态不合法")
private Integer status;*/
@MyConstraint
private String answer;
}
4.编写验证控制器
TestValidator.java
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.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.validation.Valid;
@Controller
public class TestValidator {
@GetMapping("/test")
public String showForm(User user) {
return "form";
}
@GetMapping("/results")
public String results() {
return "results";
}
@PostMapping("/test")
public String checkUser(@Valid User user, BindingResult bindingResult, RedirectAttributes attr) {
if (bindingResult.hasErrors()) {
return "form";
}
/**
* @ Description:
* 1.使用RedirectAttributes的addAttribute方法传递参数会跟随在URL后面 ,如上代码即为?name=long&age=45
* 2.使用addFlashAttribute不会跟随在URL后面,会把该参数值暂时保存于session,待重定向url获取该参数后从session中移除,
* 这里的redirect必须是方法映射路径。你会发现redirect后的值只会出现一次,刷新后不会出现了,对于重复提交可以使用此来完成。
*/
attr.addFlashAttribute("user", user);
return "redirect:/results";
}
}
5.视图文件
form.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<style type="text/css">
.warn{color:red}
</style>
<form th:action="@{/test}" th:object="${user}" method="post">
<div>
<div>
<span>姓名:</span>
<span><input type="text" th:field="*{name}"/></span>
<span class="warn" th:if="${#fields.hasErrors('name')}" th:errors="*{name}">名字错误</span>
</div>
<div>
<span>年龄:</span>
<span><input type="number" th:field="*{age}"/></span>
<span class="warn" th:if="${#fields.hasErrors('age')}" th:errors="*{age}">年龄错误</span>
</div>
<div>
<span>邮箱:</span>
<span><input TYPE="text" th:field="*{email}"/></span>
<span class="warn" th:if="${#fields.hasErrors('email')}" th:errors="*{email}">邮箱错误</span>
</div>
<div>
<span>验证答案:</span>
<span><input TYPE="text" th:field="*{answer}"/></span>
<span class="warn" th:if="${#fields.hasErrors('answer')}" th:errors="*{answer}">答案错误</span>
</div>
<div>
<span>
<button type="submit">提交</button>
</span>
</div>
</div>
</form>
</body>
</html>
results.html
和上面无异
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<body>
<div th:each="user: ${user}">
恭喜您,<span th:text="${user.name}">名字</span>(先生/女士),数据提交成功!
<div>您的年龄是:
<span th:text="${user.age}"></span></div>
<div> 您的邮箱是:
<span th:text="${user.email}"></span>
</div>
</div>
</body>
</html>
依赖如下
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
由于SpringBoot使用的是2.3,此时需要手动添加validation的依赖。
推荐阅读
-
html表单验证证件类型和证件号码匹配,并验证问题_html/css_WEB-ITnose
-
jQuery插件Validate实现自定义表单验证_jquery
-
wicket基础应用(1)--使用wicket对表单中的数据进行验证
-
SpringBoot表单验证(注解验证)@Validated使用
-
使用vue自定义指令开发表单验证插件validate.js
-
使用vue自定义指令开发表单验证插件validate.js
-
vue+elementUI实现表单和图片上传及验证功能示例
-
在ASP.NET 2.0中操作数据之十九:给编辑和新增界面增加验证控件
-
C#自定义RSA加密解密及RSA签名和验证类实例
-
JS表单数据验证的正则表达式(常用)