1.Hibernate-Validate校验框架
本文最后更新于 1547 天前,其中的信息可能已经有所发展或是发生改变。

1. 介绍

SpringBoot对表单数据校验采用了Hibernate-Validate校验框架

2. 实现

2.1 在实体类中添加校验规则

public class User {
    @NotBlank(message="不能是空空空")
    @Length(min=3,max=8)
    private String name;
    @NotEmpty
    private String password;
    @Max(value=100)
    @Min(value=0)
    private Integer age;

2.2 在Controller中开启校验

    /** 
     * 由于SpringMVC会将对象放入Model中传递,key的名称默认是该对象的类名称首字母小写,
     * 也可以用ModelAttribute("userone")控制
     * @param user
     * @return
     */
    @RequestMapping("/addUser")
    public String addUser(@ModelAttribute("userone") User user){
        return "add";
    }

    @RequestMapping("/save")
    public String ok(@ModelAttribute("userone") @Valid User user,BindingResult bindingResult){
        System.out.println("User:"+user.toString());
        if(bindingResult.hasErrors()){
            return "add";
        }
        return "ok";
    }

2.3 在页面上获取提示信息(使用了thymeleaf)

    <form th:action="@{/save}" method="post">
        用户姓名:<input type="text" name="name"/><font color="red" th:errors="${userone.name}"></font><br/>
        用户密码:<input type="password" name="password"/><font color="red" th:errors="${userone.password}"></font><br/>
        用户年龄:<input type="text" name="age"/><font color="red" th:errors="${userone.age}"></font><br/>
        <input type="submit" value="提交"/>
    </form>

3. 校验规则

  • @NotBlank:判断字符串是否为null或者空字符串,并且会去掉首位空格
  • @NotEmpty:判断字符串是否为null
  • @Lengrh:判断字符的长度(最大或者最小)
  • @Min:判断数值最小值
  • @Max:判断数值最大值
  • @Email:判断邮箱是否合法
    注:所有提示信息都可手动修改message="不能是空空空"
作者:Yuyy
博客:https://yuyy.info
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇