Spring Boot 2 + Thymeleaf:服务器端表单验证
表单验证分为前端验证和服务器端验证。
服务器端验证方面,Java提供了主要用于数据验证的JSR 303规范,而Hibernate Validator实现了JSR 303规范。
项目依赖加入spring-boot-starter-thymeleaf时,默认就会加入Hibernate Validator的依赖。
开发环境:IntelliJ IDEA 2019.2.2
Spring Boot版本:2.1.8
新建一个名称为demo的Spring Boot项目。
1、pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
2、src/main/java/com/example/demo/User.java
package com.example.demo; import org.hibernate.validator.constraints.Length; import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size; public class User {
@NotBlank(message = "用户名不能为空")
String name;
@Length(min = 11, max = 11, message = "手机号长度必须11位")
String phone;
@Size(min = 6, max = 20, message = "密码长度6-20位")
String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
3、src/main/java/com/example/demo/FormController.java
package com.example.demo; import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping; import javax.validation.Valid;
import java.util.List; @Controller
public class FormController {
@RequestMapping("/{form}")
public String form(@PathVariable String form, @ModelAttribute User user){
return form;
} @PostMapping("/submit")
public String submit(@Valid User user, BindingResult result){
if (result.hasErrors()) {
List<ObjectError> list = result.getAllErrors();
for (ObjectError error : list) {
System.out.println(error.getDefaultMessage());
}
return "form";
}
//业务逻辑处理
return "form";
} }
4、src/main/resources/templates/form.html
前端通过#fields对象输出错误信息有2种方式,1种是在每个字段后面输出,另1种是全部在一起输出。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>表单的提交处理</title>
<style>
.fieldError{color: red}
</style>
</head>
<body>
<form method="post" th:action="@{/submit}" th:object="${user}">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" th:field="*{name}" />
<span class="fieldError" th:if="${#fields.hasErrors('*{name}')}" th:errors="*{name}"></span>
</td>
</tr>
<tr>
<td>手机号:</td>
<td><input type="text" th:field="*{phone}" />
<span class="fieldError" th:if="${#fields.hasErrors('*{phone}')}" th:errors="*{phone}"></span>
</td>
</tr>
<tr>
<td>密码:</td>
<td><input type="text" th:field="*{password}" />
<span class="fieldError" th:if="${#fields.hasErrors('*{password}')}" th:errors="*{password}"></span>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="提交" />
<div th:each="err : ${#fields.errors('*')}">
<span th:text="${err}" class="fieldError"></span>
</div>
</td>
</tr>
</table>
</form>
</body>
</html>
启动服务后,浏览器访问http://localhost:8080/form,点击提交按钮,结果如下:

Spring Boot 2 + Thymeleaf:服务器端表单验证的更多相关文章
- Spring Boot笔记八:表单验证
所谓的表单验证,就是为了防止用户乱输入的,这个问题前端的HTML5就可以判断了,其实不需要后端来验证,这里还是讲一下后端验证 首先,我们的Person类,我们加上一些表单验证的注释,如下: packa ...
- spring boot快速入门 6: 表单验证
廖师兄源码: https://gitee.com/liaoshixiong/girl 样例:拦截所有未满18岁的女生 第一步:在girl实体类中:添加注解 @Min(value=18 ,message ...
- spring+thymeleaf实现表单验证数据双向绑定
前言 这个教程介绍了Thymeleaf与Spring框架的集成,特别是SpringMvc框架. 注意Thymeleaf支持同Spring框架的3.和4.版本的集成,但是这两个版本的支持是封装在thym ...
- Spring Boot 2 + Thymeleaf:表单字段绑定、表单提交处理
Spring Boot中Thymeleaf对表单处理的一些用法:(1)使用th:field属性:进行表单字段绑定(2)使用ids对象:一般用于lable配合radio或checkbox使用(3)表单提 ...
- spring boot 开发 提交form表单出错
提交表单时,字段有的没有值,springboot 会报错. org.springframework.validation.BindException: org.springframework.vali ...
- spring mvc 使用jsr-303进行表单验证的方法介绍
源代码来源:http://howtodoinjava.com/spring/spring-mvc/spring-bean-validation-example-with-jsr-303-annotat ...
- Python 服务器端表单验证插件
Python格式验证库 Cerberus 作者 MrStranger 关注 2016.08.02 14:44 字数 2140 阅读 79评论 0喜欢 1 Cerberus是一个验证Python对象.M ...
- 玩转spring boot——AOP与表单验证
AOP在大多数的情况下的应用场景是:日志和验证.至于AOP的理论知识我就不做赘述.而AOP的通知类型有好几种,今天的例子我只选一个有代表意义的“环绕通知”来演示. 一.AOP入门 修改“pom.xml ...
- Webx之表单验证
引入服务器端表单验证service,是通过在webx.xml中通过服务引入的方式完成的.例如,在user相关信息的表单验证的产生过程是这样的:webx-user.xml通过 <beans:imp ...
随机推荐
- React路由的使用 Redirect默认展示某一个页面 Switch找到停止 BrowserRouter和HashRouter 的区别
引入 Redirect 默认展示某一个页面 Switch 一旦找到 路由 就停止 不会在往下找了 App.js import {Link,Route,NavLink,Redirect,Switch} ...
- 【1】基于OpenCV的DLL动态库隐式连接
1DLL的作用 DLL是一个包含可由多个程序同时使用的代码和数据的库.例如:在Windows操作系统中,Comdlg32 DLL执行与对话框有关的常见函数.因此,每个程序都可以使用该DLL中包含的功能 ...
- Kubernetes行业调研报告:多集群、多云部署成企业首选策略
新兴的多集群.多云部署成为首选的企业策略,而边缘部署则呈上升趋势 2019年11月5日,业界采用最广泛的Kubernetes管理平台创造者Rancher Labs(以下简称Rancher)发布了首份调 ...
- Java 8——重复注解和注解的作用范围的扩大化
一.重复注解 在某些情况下,希望将相同的注解应用于声明或类型用途.从Java SE 8发行版开始,重复注解使可以执行此操作. 例如,正在编写代码以使用计时器服务,该服务使能够在给定时间或某个计划上运行 ...
- 1.编译spring源码
本文是作者原创,版权归作者所有.若要转载,请注明出处 下载spring源码,本文用的是版本如下: springframework 5.1.x, IDE工具idea 2019.2.3 JAVA ...
- Dubbo学习系列之十一(Dashboard+Nacos规则推送)
中国武术,门派林立,都是号称多少代的XXX传人,结果在面对现代武术时,经常被KO秒杀,为啥,光靠宣传和口号撑门面,终究是靠不住,必须得有真货 ,得经得住考验,所以不能只说Sentinel有多好,也得给 ...
- 知道内存中一个图片的指针IntPtr大小,转换成图片显示
//nSize 为总长度//pImageData 为总数据//nImageSize //一个图片的长度 byte[] _bytes = new byte[nImageSize];// //IntPtr ...
- 红黑树原理详解及golang实现
目录 红黑树原理详解及golang实现 二叉查找树 性质 红黑树 性质 operation 红黑树的插入 golang实现 类型定义 leftRotate RightRotate Item Inter ...
- JS---part2课程介绍+part1复习
part1复习 JavaScript分三个部分: 1. ECMAScript标准----JS基本的语法 2. DOM:Document Object Model 文档对象模型 3. BOM:浏览器对象 ...
- dnf & yum
CentOS8 配置软件源 在 CentOS8 中.使用了基于DNF技术(YUM v4)的 YUM 工具. YUM v4 与之前在 CentOS7 上使用的 YUM v3 相比具有以下优点: 提高性能 ...