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

错误信息中文乱码的问题
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的编辑器会自动处理文件的编码和解码。

posted @ 2019-02-21 15:31  阿Yo  阅读(600)  评论(0编辑  收藏  举报