gpt4 book ai didi

Spring Boot文档阅读笔记-Validating Form Input解析

转载 作者:知者 更新时间:2024-03-12 23:35:34 24 4
gpt4 key购买 nike

这篇文章的主要功能是Web应用程序中验证表单输入是否合法的文章。

PersonForm对象

首先创建一个PersonForm对象:

这个对象会验证PersonForm的用户名,代码如下:

package cn.it1995;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

public class PersonForm {

    @NotNull
    @Size(min = 2, max = 30)
    private String name;

    @NotNull
    @Min(18)
    private Integer age;

    public String getName() {

        return name;
    }

    public void setName(String name) {

        this.name = name;
    }

    public Integer getAge() {

        return age;
    }

    public void setAge(Integer age) {

        this.age = age;
    }

    @Override
    public String toString() {

        return "PersonForm{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

PersonForm类有两个成员,name和age,下面给出3个限制方面的注解:

①@Size(min=2, max=30):限制字符的长度为2~30个字符;

②@NotNull:禁止值为null;

③@Min(18):限制最小也要18个字符。

上面的PersonForm类还有对应的get、set、toString方法。

创建Controller

这里简单创建一个Web Controller,代码如下:

package cn.it1995;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.validation.Valid;

@Controller
public class WebController implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {

        registry.addViewController("/results").setViewName("results");
    }

    @GetMapping("/")
    public String showForm(PersonForm personForm){

        return "form";
    }

    @PostMapping("/")
    public String checkPersonInfo(@Valid PersonForm personForm, BindingResult bindingResult){

        if(bindingResult.hasErrors()){

            return "form";
        }

        return "redirect:/results";
    }
}

这里的Controller包含“/”路径下的,GET和POST方法。

showForm方法返回form的模板,这个模板调用了PersonForm。

checkPersonInfo方法有两个参数:

①personForm对象,使用@Valid收集表格属性。

②bindingResult对象,验证错误。

如果验证全部都是正确的,就跳到results模板中。

HTML相关

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="#" th:action="@{/}" th:object="${personForm}" method="post">
        <table>
            <tr>
                <td>Name:</td>
                <td><input type="text" th:field="*{name}" /></td>
                <td th:if="${#fields.hasErrors('name')}" th:error="*{name}">Name Error</td>
            </tr>
            <tr>
                <td>Age:</td>
                <td><input type="text" th:field="*{age}"/></td>
                <td th:if="${#fields.hasErrors('age')}" th:errors="*{age}">Age Error</td>
            </tr>
            <tr>
                <td><button type="submit">Submit</button></td>
            </tr>
        </table>
    </form>
</body>
</html>

form.html代码如下:

<html>
<body>
Congratulations! You are old enough to sign up for this site.
</body>
</html>

Maven相关

对应的mavn如下:

<?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>org.example</groupId>
    <artifactId>ValidatingDemo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <lombok.version>1.16.18</lombok.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.1.10.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
            <version>2.3.12.RELEASE</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.2.2.RELEASE</version>
            </plugin>
        </plugins>
    </build>

</project>

程序运行

程序运行截图如下;

点击提交后:

源码打包下载地址:

Java/ValidatingDemo at master · fengfanchen/Java · GitHub

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com