Spring常用表单验证注解

in TCEHJava with 0 comment

@AssertFalse

@AssertTrue

@DecimalMax(value=x)

@DecimalMin(value=x)

@Digits(integer=整数位数, fraction=小数位数)

@Future

@Max(value=x)

@Min(value=x)

@NotNull

@Null

@Past

@Pattern(regex=正则表达式, flag=)

@Size(min=最小值, max=最大值)

@Valid

@NotEmpty

@Range(min=最小值, max=最大值)

@NotBlank

@Length(min=下限, max=上限)

@Email

简单使用示例

标记校验注解

package com.example.demo.entity;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;

public class Person {
    // 标记校验name不为空
    @NotBlank
    private String name;
    // 标记校验age大于等于18
    @Min(value = 18)
    private int age;

    private String sex;

    private float high;

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public float getHigh() {
        return high;
    }

    public void setHigh(float high) {
        this.high = high;
    }

    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + ", sex=" + sex + ", high=" + high + "]";
    }

}

启用校验注解@Valid

package com.example.demo.controller;

import java.util.List;

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.entity.Person;

@Controller
public class DemoController {
    /**
     * 通过@Valid注解,标记启动校验。BindingResult对象获取校验结果
     * @param person 
     * @param result
     * @return
     */
    @RequestMapping("/test")
    @ResponseBody
    public String parseJsonToEntity(@RequestBody @Valid Person person, BindingResult result) {
        List<ObjectError> allErrors = result.getAllErrors();
        if (result.hasErrors()) {
            return JSONObject.toJSONString(allErrors);
        }
        return person.toString();
    }
}
Comments are closed.