這篇文篇主要簡(jiǎn)述如何在springboot中驗(yàn)證表單信息。在springmvc工程中,需要檢查表單信息,表單信息驗(yàn)證主要通過(guò)注解的形式。
構(gòu)建工程創(chuàng)建一個(gè)springboot工程,由于用到了 web 、thymeleaf、validator、el,引入相應(yīng)的起步依賴(lài)和依賴(lài),代碼清單如下:
創(chuàng)建一個(gè)PresonForm的Object類(lèi)org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-starter-thymeleaf org.hibernate hibernate-validator org.apache.tomcat.embed tomcat-embed-el
package com.forezp.entity; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * Created by fangzhipeng on 2017/4/19. */ public class PersonForm { @NotNull @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 + ")"; } }
這個(gè)實(shí)體類(lèi),在2個(gè)屬性:name,age.它們各自有驗(yàn)證的注解:
@Size(min=2, max=30) name的長(zhǎng)度為2-30個(gè)字符 @NotNull 不為空 @Min(18)age不能小于18創(chuàng)建 web Controller
@Controller public class WebController extends WebMvcConfigurerAdapter { @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"; } }創(chuàng)建form表單
src/main/resources/templates/form.html:
注冊(cè)成功的頁(yè)面
src/main/resources/templates/results.html:
html> Congratulations! You are old enough to sign up for this site.