转自: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. Java内存机制,内存地址

    问题一:String str1 = "abc"; String str2 = "abc"; System.out.println(str1==str2); // ...

  2. dhtmlxtree动态加载节点数据的小随笔

    最近做了一个这个东西,颇有些感触,随笔记录一下自己的过程. 首先特别感谢:https://blog.csdn.net/cfl20121314/article/details/46852591,对我的帮 ...

  3. HIVE 命令记录

    HIVE 命令记录 设置hive运行的队列 hive> set mapreduce.job.queuename=ven12; 打印列名 hive> set hive.cli.print.h ...

  4. Deutsch lernen (05)

    1. die Wahrheit, -en 真理:  - 真言,实情 Wir sollen die Wahrheit festhalten. 坚持:紧握 Im Wein liegt Wahrheit. ...

  5. MatLab之HDL coder

    1 Workflow The workflow for applying HDL code generation to the hardware design process requires the ...

  6. Java中final,finally和finalize区别

    Day11_SHJavaTraing_4-18-2017 Java中final,finally和finalize区别 1.final—修饰符(关键字) ①final修饰类,表示该类不可被继承 ②fin ...

  7. CMMI评估流程

    原文链接:http://www.cmmcn.com/new/cmmi-105.html 当前位置:首页 >> CMMI知识库 >> CMMI相关 >> CMMI评估 ...

  8. 【转】虚拟化(四):vsphere高可用功能前提-共享存储搭建

    vsphere高级功能HA.DRS.FT等,都需要有共享存储环境,即多台esxi主机同时连接一个共享存储,这样在新建虚拟机时,可以指定把虚拟磁盘保存在共享存储上,便于虚拟机在各个主机之间“飘移”. 常 ...

  9. JDK8新特性:Lambda表达式

    Lambda表达式,案例一:new Thread(() -> System.out.println("thread")); Lambda表达式,案例二:由参数/箭头和主体组成 ...

  10. shell脚本—基础知识,变量

    shell脚本本质: 编译型语言 解释型语言 shell编程基本过程 1.建立shell文件 2.赋予shell文件执行权限,使用chmod命令修改权限 3.执行shell文件 shell变量: sh ...