转自: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;
} }

12两处通过简单的标注设定了验证规则,@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进行表单验证的更多相关文章

  1. Spring Boot 表单验证、AOP统一处理请求日志、单元测试

    一.使用@Valid表单验证 于实体类中添加@Min等注解 @Entity public class Girl { @Id @GeneratedValue private Integer id; pr ...

  2. Spring MVC 表单验证

    1. 基于 JSR-303(一个数据验证的规范): import javax.validation.constraints.Min; import javax.validation.constrain ...

  3. spring boot 表单验证

    1 设置某个字段的取值范围 1.1 取值范围验证:@Min,@Max ① 实例类的属性添加注解@Min ② Controller中传入参数使用@Valid注解 1.2 不能为空验证:@NotNull ...

  4. Spring常用表单验证注解

    下面是主要的验证注解及说明: 注解 适用的数据类型 说明 @AssertFalse Boolean, boolean 验证注解的元素值是false @AssertTrue Boolean, boole ...

  5. 玩转spring boot——AOP与表单验证

    AOP在大多数的情况下的应用场景是:日志和验证.至于AOP的理论知识我就不做赘述.而AOP的通知类型有好几种,今天的例子我只选一个有代表意义的“环绕通知”来演示. 一.AOP入门 修改“pom.xml ...

  6. Spring表单验证

    表单验证 给表单添加验证的步骤如下 1.在 pom.xml 里添加 hibernate-validator 依赖http://hibernate.org/validator/documentation ...

  7. spring mvc:练习:表单验证(javaConfig配置和注解)

    使用Spring表单标签, 表单验证使用 JSR303 的验证注解,hibernate-validators,提供了使用MessageSource和访问静态资源(如CSS,JavaScript,图片) ...

  8. spring+thymeleaf实现表单验证数据双向绑定

    前言 这个教程介绍了Thymeleaf与Spring框架的集成,特别是SpringMvc框架. 注意Thymeleaf支持同Spring框架的3.和4.版本的集成,但是这两个版本的支持是封装在thym ...

  9. Spring Boot学习——表单验证

    我觉得表单验证主要是用来防范小白搞乱网站和一些低级的黑客技术.Spring Boot可以使用注解 @Valid 进行表单验证.下面是一个例子. 例子说明:数据库增加一条Student记录,要求学生年龄 ...

随机推荐

  1. web前端利用HTML代码显示符号

    HTML常用符号代码:                       ´ ´ © © > > µ µ ® ® & & ° ° ¡ ¡     » » ¦ ¦ ÷ ÷ ¿ ¿ ...

  2. linux 新添加的硬盘格式化并挂载到目录下

    需求: 新增加一块硬盘sdb,将sdb分区,只分一个区,格式化,挂载到目录/ssd下. 1.  查看现在已有的分区状态 # df –l 图中显示,没有看到sdb硬盘 2.  查看服务器安装的硬盘状态( ...

  3. openMSP430之Custom linker script

    The use of the -mmcu switch is of course NOT mandatory. It is simply a convenient way to use the pre ...

  4. WebGL画点程序v1

    本文程序实现画一个点的任务,如下图.其中,点的位置直接给定("硬编码")在顶点着色器中. 整个程序包含两个文件,分别是: 1. HelloPoint1.html <!DOCT ...

  5. ApplicationLoader登录失败

    报错:Please sign in with an app-specific password. You can create one at appleid.apple.com 是因为帐号开启了双重认 ...

  6. 初探CORBA组件化编程

    1.掌握组件化开发的概念,了解CORBA模型及ORB机制:2.掌握CORBA组件编程方法.二.实验内容(一).步骤1.配制环境JDK环境.2.编写编译IDL接口.3.编写编译服务端程序.4.编写编译客 ...

  7. Python【每日一问】35

    问: 基础题: 从键盘输入4个数字,各数字采用空格分隔,对应为变量x0,y0,x1,y1.计算(x0,y0)和(x1,y1)两点之间的距离,输出结果保留1位小数. 比如,键盘输入:0 1 3 5,屏幕 ...

  8. 15.5.1【Task实现细节】 生成的代码

    还在吗?我们开始吧.由于深入讲解需上百页的篇幅,因此这里我不会讲得太深.但我会提 供足够的背景知识,以有助于你对整个结构的理解.之后可通过阅读我近些年来撰写的博客文章, 来了解更加错综复杂的细节,或简 ...

  9. [Ynoi2011]D1T1

    题目大意: 给定一个序列$a_1,a_2,\dots,a_n$,进行$m$次操作,每次操作如下: 1. 给定$x,y,z$,对所有下标为$y,y+x,y+2x,\dots$的元素加上$z$(保证$y\ ...

  10. linux下关闭键盘的重复击键

    https://askubuntu.com/questions/576421/disable-keyboard-repeat-from-command-line You can use the xse ...