java springcloud版b2b2c社交电商spring cloud分布式微服务 (十九) 验证表单信息

这篇文篇主要简述如何在springboot中验证表单信息。在springmvc工程中,需要检查表单信息,表单信息验证主要通过注解的形式。

构建工程

创建一个springboot工程,由于用到了 web 、thymeleaf、validator、el,引入相应的起步依赖和依赖,代码清单如下:


        
            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
        
    

创建一个PresonForm的Object类

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 + ")";
    }
}

这个实体类,在2个属性:name,age.它们各自有验证的注解:

  • @Size(min=2, max=30) name的长度为2-30个字符
  • @NotNull 不为空
  • @Min(18)age不能小于18

创建 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";
    }
}

创建form表单
src/main/resources/templates/form.html:


    
        
Name: Name Error
Age: Age Error

电子商务社交平台源码请加企鹅求求:叁五叁六贰四柒贰五九

你可能感兴趣的:(java springcloud版b2b2c社交电商spring cloud分布式微服务 (十九) 验证表单信息)