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

posted on 2018-03-28 17:59  Sharpest  阅读(209)  评论(0编辑  收藏  举报