表单验证

给表单添加验证的步骤如下

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} 个字符

错误信息中文乱码的问题
https://stackoverflow.com/questions/4659929/how-to-use-utf-8-in-resource-properties-with-resourcebundle

使用 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的编辑器会自动处理文件的编码和解码。

最新文章

  1. 记一次tomcat线程创建异常调优:unable to create new native thread
  2. 同感,C#对JSON序列化和反序列化有点蹩脚
  3. EF连接ORACLE
  4. C# 调用restful服务开源库
  5. Aoite 系列(02) - 超动感的 Ioc 容器
  6. Linux的文件时间
  7. bzoj1008 [HNOI2008]越狱
  8. 【4_237】Delete Node in a Linked List
  9. socket.io 入门教程
  10. linux远程客户端putty,xshell搭建注意事项——《视频》
  11. Python模块整理(三):子进程模块subprocess
  12. oracle10~11g在centos5~6版本上安装整体总结如下
  13. Xcode快捷键 (本人总结常用的)
  14. JMeter简单的性能测试实例
  15. SSIS从理论到实战,再到应用(7)----常用的数据类型转换操作
  16. TRILL浅析
  17. css多重边框
  18. C++函数重载,重写,重定义
  19. DevOps知识地图实践指南
  20. 与元素类型 &quot;item&quot; 相关联的 &quot;name&quot; 属性值不能包含 &#39;&lt;&#39; 字符。

热门文章

  1. UNITY WWW使用代码
  2. Python全栈工程师(Python3 所有基础内容 0-0)
  3. C# 与 Java Rsa加密与解密互通
  4. udp调优经验
  5. JetBrains全家桶激活地址
  6. netstat/lsof
  7. msdn 硬盘
  8. linux查看端口号监听状态
  9. 使用delphi 开发多层应用(二十一)使用XE5 RESTClient 直接访问kbmmw 数据库
  10. mvc api odata查询选项之 $inlinecount $format 选项(转)