Spring表单验证
表单验证
给表单添加验证的步骤如下
1.在 pom.xml 里添加 hibernate-validator 依赖
http://hibernate.org/validator/documentation/
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.4.3.Final</version>
</dependency>
注意版本的问题,在 Maven 依赖小计中说过。
2.给表单实体类添加注解
public class PersonForm {
@NotNull
@Size(min=2, max=30, message = "{personForm.name}")
private String name;
@NotNull
@Min(18)
private Integer age;
}
3.修改控制器的方法
https://spring.io/guides/gs/validating-form-input/#_create_a_web_controller
@PostMapping("/")
public String checkPersonInfo(@Valid PersonForm personForm, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "form";
}
return "redirect:/results";
}
(1) 用 @Valid 标记表单对象参数
(2) 紧挨着 personForm 加一个 BindingResult bindingResult
4.在JSP页面上添加显示错误的项
用 <form:errors> 标签在页面上显示错误信息
<td><form:input path="name"/><form:errors path="name"/></td>
ps.本地化,把错误提示信息放在资源文件中
添加 /src/main/resources/ValidationMessages.properties 文件
personForm.name = 用户名限制 {min} ~ {max} 个字符
使用 native2ascii 命令转换文件编码
native2ascii -encoding UTF-8 text_utf8.properties text.properties
在 Intellij IDEA 中的操作
https://www.jetbrains.com/help/idea/properties-files.html
在 Settings->Editor->File Encodings 中勾选 Transparent native-to-ascii conversion 。
设置好后IDEA的编辑器会自动处理文件的编码和解码。
最新文章
- 记一次tomcat线程创建异常调优:unable to create new native thread
- 同感,C#对JSON序列化和反序列化有点蹩脚
- EF连接ORACLE
- C# 调用restful服务开源库
- Aoite 系列(02) - 超动感的 Ioc 容器
- Linux的文件时间
- bzoj1008 [HNOI2008]越狱
- 【4_237】Delete Node in a Linked List
- socket.io 入门教程
- linux远程客户端putty,xshell搭建注意事项——《视频》
- Python模块整理(三):子进程模块subprocess
- oracle10~11g在centos5~6版本上安装整体总结如下
- Xcode快捷键 (本人总结常用的)
- JMeter简单的性能测试实例
- SSIS从理论到实战,再到应用(7)----常用的数据类型转换操作
- TRILL浅析
- css多重边框
- C++函数重载,重写,重定义
- DevOps知识地图实践指南
- 与元素类型 ";item"; 相关联的 ";name"; 属性值不能包含 &#39;<;&#39; 字符。