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记录,要求学生年龄 ...
随机推荐
- 快速搭建tab
1. 布局文件代码: <?xml version="1.0" encoding="utf-8"?> <android.support.v4.a ...
- Scala——面向对象和函数式编程语言
Scala Scala是一门运行时基于JVM的编程语言,具备函数式编程和面向对象特点. 基本知识 basics 任意词均可作为符号名,对于关键词,以反引号包裹,避免使用下划线,避免带美元符的名字. 声 ...
- 【PostgreSQL-9.6.3】表继承
表继承是PostgreSQL特有的,子表可以从父表中继承字段和一些属性.例如: --创建一张表“persons”作为父表: test=# create table persons ( test(# i ...
- Interrupt中断线程
package com.wistron.swpc.ecs.util; public class WrongWayStopThread extends Thread{ public static voi ...
- PAC学习理论:机器学习那些事
参考翻译,有大量删除和修改,如有异议,请拜访原文.一定要看英文原文!!!. 本文转载于:深度译文:机器学习那些事 英文[原题]A Few Useful Things to Know About Mac ...
- EnforceLearning-主动强化学习
前言: 被动学习Agent由固定的策略决定其行为.主动学习Agent必须自己决定采取什么行动. 具体方法是: Agent将要学习一个包含所有行动结果概率的完整模型,而不仅仅是固定策略的模型: 接下来, ...
- C++泛型 && Java泛型实现机制
C++泛型 C++泛型跟虚函数的运行时多态机制不同,泛型支持的静态多态,当类型信息可得的时候,利用编译期多态能够获得最大的效率和灵活性.当具体的类型信息不可得,就必须诉诸运行期多态了,即虚函数支持的 ...
- C#—接口和抽象类的区别?
一.接口 接口是指对协定进行定义的引用类型,其他类型实现接口,以保证它们支持某些操作.接口指定必须由类提供的成员或实现它的其他接口.与类相似,接口可以包含方法.属性.索引器和事件作为成员. 1.接口存 ...
- Java+selenium+Firefox/ IE/ Chrome主流浏览器自动化环境搭建
一.java+selenium+firefox 1.环境准备:JDK1.8 2.安装firefox浏览器v59 3.下载驱动:https://github.com/mozilla/geckodrive ...
- 团体程序设计天梯赛-练习集-L1-047. 装睡
L1-047. 装睡 你永远叫不醒一个装睡的人 —— 但是通过分析一个人的呼吸频率和脉搏,你可以发现谁在装睡!医生告诉我们,正常人睡眠时的呼吸频率是每分钟15-20次,脉搏是每分钟50-70次.下面给 ...