【Spring】官网教程阅读笔记(七):验证Form表单

【前言】内个验证表单的功能很常用,平时我在servlet实现web server的时候,依照客户端验证的原则,用jsp校验表单中的submit。比如jsp里面一个表单

<form method="post" name="uploadform" enctype="multipart/form-data" οnsubmit="return validate_form(this)">

<input type="submit" id="submitbt" value="上传">

</form>
用下面的函数验证(注意,验证的每个分支要有明确的return false/true;否则form表单在提交后会一片空白)

function validate_required(field,alerttxt)
{
with (field)
  {
  if (value==null||value=="")
    {alert(alerttxt);return false}
  else {return true}
  }
}

function validate_form(thisform)
{
with (thisform)
  {
  	if (validate_required(appFile,"请选择上传文件")==false)
   	 {versionCode.focus();return false}
  	else if(validate_required(versionCode,"请输入版本号")==false)
     {versionCode.focus();return false}
  	else {return true;}
  }
}

现在来看看Spring是怎么做数据验证的。原文链接


【实现目标】在这里我们建立一个简单的MVC应用,他能够接受用户输入,并对该输入用标准注解做校验。我们还会展示如何在屏幕上显示标准错误信息,这样用户可以得到提示一般重新输入正确的值。

【准备工作】pom.xml配置

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
        </dependency>
		<dependency>
			<groupId>org.apache.tomcat.embed</groupId>
			<artifactId>tomcat-embed-el</artifactId>
		</dependency>
    </dependencies>

创建一个Person对象

这应用将会校验用户名和年龄,所以首先我们需要建立一个表示人的类

<span style="font-size:14px;">package hello;

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

public class Person {

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

    @NotNull
    @Min(18)
    private Integer age;

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String toString() {
        return "Person(Name: " + this.name + ", Age: " + this.age + ")";
    }

}</span>

这个Person类有两个属性,一个名字一个年龄。他们被标记上了一些标准验证注解:

@Size(min=2, max=30) 只用许name2到30字节的长度;

@NotNull 不允许空值,这个空值是在没输入的情况下由Spring MVC自动生成的;

@Min(18) age低于18是不允许的(等于18可以)

另外,你还可以看到getter和setter,还有toString()

建立Web Controller

既然我们已经定义了一个实体,现在创建一个简单的Web Controller

package hello;

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;


@Controller
public class WebController extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/results").setViewName("results");
    }

    @RequestMapping(value="/", method=RequestMethod.GET)
    public String showForm(Person person) {
        return "form";
    }

    @RequestMapping(value="/", method=RequestMethod.POST)
    public String checkPersonInfo(@Valid Person person, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return "form";
        }
        return "redirect:/results";
    }

}
这个控制器有针对GET和POST的方法,都映射在/目录上。

showForm方法返回form模板。在方法签名中包含一个Person对象,因而form模板可以从form属性中导入一个Person对象。

checkPersonInfo方法接受两个参数:

  • 一个person对象,被标记为@Valid来保证在表单里填入的属性合法;
  • 一个bindingResult对象,用了测试和检索合法性错误。
你可以检索从form边界到Person对象的所有的属性。在代码中,你测试了错误,如果出错了将把访问者返回到开始的form模板
如果所有的Person属性都是合法的,控制器将访问页面重定向到最终的results模板。(重定向我们这是第二次看见了,在第六节了也见过类似"redirect:/results"这种重定向的形式)

创建HTML的front和foot

现在我们创建"main"页面form.html
<html>
    <body>
        <form action="#" th:action="@{/}" th:object="${person}" method="post">
            <table>
                <tr>
                    <td>Name:</td>
                    <td><input type="text" th:field="*{name}" /></td>
                    <td th:if="${#fields.hasErrors('name')}" th:errors="*{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}">Name Error</td>
                </tr>
                <tr>
                    <td><button type="submit">Submit</button></td>
                </tr>
            </table>
        </form>
    </body>
</html>
这个页面包含一个简单的form表单,表单里每个域都在单独的表格里。表单配置为/访问路径。表单被controller中GET对应方法所属的Person对象标记出来,这就是bean-backed form(度娘上没这个term的翻译,我斗胆翻成后台bean表单)。Person有两个域,你可以看到他们分别被标记为th:field="{name}"和th:field="{age}",紧随其后的是表示验证错误的元素。
最后,你有一个提交的button。一般来说,如果用户输入一个名字或年龄违反了@Valid限制符,它将返回到这个页面并带有错误信息显示出来。如果输入的有效的名字和年龄,用户会进入到下一个web页。

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

创建Application类

这个应用中,我们使用Thymeleaf语言模板。这个应用需要除了HTML之外更多的特性。
package hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }

}

其实Application类和以往没有区别。这是因为注解@SpringBootApplication涵盖了搜索@EnableWebMvc的功能,同样还涵盖了搜索@Controller类及其方法。
Thymeleaf配置同样由@SpringBootApplication涵盖:默认的模板置于classpath下的templates/路径下,并被解析为"以剥离.html后缀留下的文件名解析为名”的view。

Build并执行JAR

很简单。不再贴图了。

【小结】
我们通过给Bean中的域加注解@Min @Size @NotNull来打到约束输入值的目的,同时需要在web controller当中的POST方法参数使用注解@Valid。
【疑问】这种验证方式是在后端进行的还是在前端进行的呢?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值