Spring进行表单验证
转自:https://www.tianmaying.com/tutorial/spring-form-validation
开发环境
- IDE+Java环境(JDK 1.7或以上版本)
- Maven 3.0+(Eclipse和Idea IntelliJ内置,如果使用IDE并且不使用命令行工具可以不安装)
POM文件如下:
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tianmaying</groupId>
<artifactId>springboot-form-validation-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot-form-validation-demo</name>
<description>Springboot form validation demo</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.5.RELEASE</version>
<relativePath/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
通过标注设置验证规则
我们需要验证的是提交上来的HelloMessage信息,因此我们给这个类增加标注。我们希望打招呼的对象(name属性)的长度是2到30之间,打招呼的内容(message属性)的长度是10到300之间。让我们来看看如何进行标注:
HelloMessage.java
package com.tianmaying.springboot.formvalidation;
import javax.validation.constraints.Size;
public class HelloMessage {
@Size(min=2, max=30) // 1
private String name;
@Size(min=10, max=300)// 2
private String message;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
1和2两处通过简单的标注设定了验证规则,@Size(min=2, max=30)表示对应属性的字符串长度必须在2到30之间。当然,用于描述验证的规则的标注还有很多,大家可以去异步这里了解。
在Controller中进行验证
Controller中的代码相比无表单验证时,有了几处小的修改:
SayHelloController.java
@RequestMapping(value="/sayhello", method=RequestMethod.POST)
public String sayHello(@Valid HelloMessage helloMessage, BindingResult bindingResult, Model model) {
if (bindingResult.hasErrors()) {
return "sayhello";
}
model.addAttribute("helloMessage", helloMessage);
return "message";
}
在sayHello方法中包含了三个参数,HelloMessage参数是表单绑定的待验证的对象,BindingResult包含了验证结果信息,可以通过bindingResult.hasErrors()来判断验证是否通过,Model参数则是用来保存所有用于渲染View的数据。这里的逻辑时如果验证包含错误则返回原页面(这是页面中会显示出错误信息),验证通过则显示message.html页面。
注意
BindingResult参数必须紧跟着HelloMessage参数,否则可能无法得到正确的验证结果。
错误信息的显示
为了让提交表单的页面能够在验证有错误时显示错误信息,我们需要增加一些显示错误信息的HTML代码。
sayhello.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>天码营经验: Spring表单验证</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>表单处理演示</h1>
<form action="#" th:action="@{/sayhello}" th:object="${helloMessage}" method="post">
<p>friend: <input type="text" th:field="*{name}" /></p>
<p th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Name Error</p>
<p>message: <input type="text" th:field="*{message}" /></p>
<p th:if="${#fields.hasErrors('message')}" th:errors="*{message}">message Error</p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</body>
</html>
th:object="{helloMessage}"表示这是一个bean-backed的表单,在每个表单域的后面,都跟随着一个<P>元素来显示错误验证错误信息,比如<p th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Name Error</p>。
Run起来
不解释,看这里
package com.tianmaying.springboot.formvalidation;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
这样表单验证就圆满成功啦!再来总结一下,基于Spring进行表单验证你只需要这三步:
- 通过标注设置验证规则,注意你还可以使用一些扩展实现提供的规则,比如验证是否为合法的email
- 在Controller中通过
@Valid标注和BindingResult进行规则验证 - 在页面中展现规则,如果是返回JSON的REST服务,则不需要在页面中显示,在Controller中要根据
BindingResult的结果生成对应的JSON数据
转自:https://www.tianmaying.com/tutorial/spring-form-validation
参考代码要获取本文的参考代码,请访问:https://www.tianmaying.com/tutorial/spring-form-validation/repo
Spring进行表单验证的更多相关文章
- Spring Boot 表单验证、AOP统一处理请求日志、单元测试
一.使用@Valid表单验证 于实体类中添加@Min等注解 @Entity public class Girl { @Id @GeneratedValue private Integer id; pr ...
- Spring MVC 表单验证
1. 基于 JSR-303(一个数据验证的规范): import javax.validation.constraints.Min; import javax.validation.constrain ...
- spring boot 表单验证
1 设置某个字段的取值范围 1.1 取值范围验证:@Min,@Max ① 实例类的属性添加注解@Min ② Controller中传入参数使用@Valid注解 1.2 不能为空验证:@NotNull ...
- Spring常用表单验证注解
下面是主要的验证注解及说明: 注解 适用的数据类型 说明 @AssertFalse Boolean, boolean 验证注解的元素值是false @AssertTrue Boolean, boole ...
- 玩转spring boot——AOP与表单验证
AOP在大多数的情况下的应用场景是:日志和验证.至于AOP的理论知识我就不做赘述.而AOP的通知类型有好几种,今天的例子我只选一个有代表意义的“环绕通知”来演示. 一.AOP入门 修改“pom.xml ...
- Spring表单验证
表单验证 给表单添加验证的步骤如下 1.在 pom.xml 里添加 hibernate-validator 依赖http://hibernate.org/validator/documentation ...
- spring mvc:练习:表单验证(javaConfig配置和注解)
使用Spring表单标签, 表单验证使用 JSR303 的验证注解,hibernate-validators,提供了使用MessageSource和访问静态资源(如CSS,JavaScript,图片) ...
- spring+thymeleaf实现表单验证数据双向绑定
前言 这个教程介绍了Thymeleaf与Spring框架的集成,特别是SpringMvc框架. 注意Thymeleaf支持同Spring框架的3.和4.版本的集成,但是这两个版本的支持是封装在thym ...
- Spring Boot学习——表单验证
我觉得表单验证主要是用来防范小白搞乱网站和一些低级的黑客技术.Spring Boot可以使用注解 @Valid 进行表单验证.下面是一个例子. 例子说明:数据库增加一条Student记录,要求学生年龄 ...
随机推荐
- Flex使用总结
最近做的项目因为对浏览器的兼容要求是IE10以上,所以大胆的使用了Flex布局,这里总结一些使用心得仅供参考. 一,Flex简单介绍 Flex是Flexible Box的缩写,意为”弹性布局”.任何一 ...
- 八:前端---Vue下的国际化处理
1:首先安装 Vue-i8n npm install vue-i18n --save 注:-save-dev是指将包信息添加到devDependencies,表示你开发时依赖的包裹. -save是指将 ...
- 浅谈ByteBuffer转换成byte[]时遇到的问题
有些时候我们要把ByteBuffer转换成byte[]来使用.于是很多时候会用以下代码来转换: ByteBuffer buf; .....(一些往buffer写数据的操作) byte[] bs= ne ...
- H265
H265 h265 一.名词 CTU: 编码树单元 CU: 编码单元 PU: 以CU为根,对CU进行划分,一个预测单元PU包含一个亮度预测块PB和两个色度预测块PB. TU: 以CU为根,变换单元T ...
- 【Oracle】数据迁移工具(1):SQL Loader
SQL Loader是一种数据加载工具,可以把外部数据加载到Oracle数据库中.SQL Loader中的参数有很多,本文只在第一部分中列出常用参数.要想运用SQL Loader工具 ,需要我们编辑一 ...
- C#访问Win 32的一些尝试
使用C#调用Win 32 Api大部分情况下基本只涉及到参数类型的转变,但在遇到Win 32 Api返回LPVOID *lpBuff 时会遇到一些解析遍历难题.lpBuff为二维指针,*lpBuff是 ...
- css单双行样式
#random_box li:nth-child(odd) {//双行 background: #fff5c4; } #random_box li:nth-child(even) {//单行 back ...
- PAT_A1119 Pre- and Post-order Traversals
Source: PAT A1119 Pre- and Post-order Traversals (30 分) Description: Suppose that all the keys in a ...
- SPLAY or SPALY ?
写在前面: 由我们可爱的Daniel Sleator和Robert Tarjan提出的一种数据结构,平衡树的一种,本质是二叉树. 至于到底是splay还是spaly,我认为可能splay更对一些 毕竟 ...
- 从读写分离到 CQRS,张大胖是如何解决性能问题的?
转自:https://mp.weixin.qq.com/s/rpiYZkxiLKa77OFw8XaBwA 不堪重负的数据库 张大胖公司的数据库已经不堪重负了. 这个系统最早是两个实习生写的, 按照最初 ...