日期格式
public class Monster() {@DateTimeFormat(pattern = "yyyy-MM-dd")private Date birthday;
}
输入:2024-11-12,
输出:Monster{birthday=Sun Nov 12 00:00:00 CST 2024}
public class Monster {@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")private Date birthday;
}
Json格式输入:{"birthday": "2024-11-12 15:30:00"}
输出:Monster{birthday=Sat Nov 12 15:30:00 CST 2024}
JSR303校验
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-validation</artifactId>
</dependency>
public class Monster {private Integer id;@NotEmptyprivate String email;@NotNull(message = "age不能为空")@Range(min = 1,max = 100)private Integer age;@NotEmptyprivate String name;@NotNull(message = "生日不能为空")@DateTimeFormat(pattern = "yyyy-MM-dd")private Date birthday;@NotNull(message = "薪水不能为空")@NumberFormat(pattern = "###,###.##")private Float salary;
}
1、 使用@Valid 开启对 monster 数据按照注解进行验证
2、Errors errors 表示如果校验出现错误,将校验的错误信息保存 errors
3、Map<String, Object> map 表示如果校验出现错误, 将校验的错误信息保存,map 同时保存monster对象
@RequestMapping(value = "/save")public String save(@Valid Monster monster, Errors errors, Map<String, Object> map) {System.out.println("----monster---" + monster);//我们为了看到验证的情况,我们输出map 和 errorsSystem.out.println("===== map ======");for (Map.Entry<String, Object> entry : map.entrySet()) {System.out.println("key= " + entry.getKey() + " value=" + entry.getValue());}System.out.println("===== errors ======");if (errors.hasErrors()) {//判断是否有错误List<ObjectError> allErrors = errors.getAllErrors();for (ObjectError error : allErrors) {System.out.println("error=" + error);}return "datavalid/monster_addUI";}return "datavalid/success";}
map:输出对象信息,并且会显示有几个错误,输出错误信息(跟Errors功能一样)
Errors:输出错误信息
回显错误信息
<form:form action="save" method="post" modelAttribute="monster">妖怪名字: <form:input path="name"/> <form:errors path="name"/> <br><br>妖怪年龄~: <form:input path="age"/> <form:errors path="age"/> <br><br>电子邮件: <form:input path="email"/> <form:errors path="email"/> <br><br>妖怪生日: <form:input path="birthday"/> <form:errors path="birthday"/> <br>妖怪薪水: <form:input path="salary"/> <form:errors path="salary"/> <br><input type="submit" value="添加妖怪"/>
</form:form>