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

转载于:https://www.cnblogs.com/a1518915457/p/10412881.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值