Spring MVC 表单验证

时间:2022-01-20 15:49:08

1. 基于 JSR-303(一个数据验证的规范):

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotBlank; public class User { private String username; private String password; private int age; @NotBlank(message="用户名不能为空")
public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} @NotNull(message="密码不能为null")
public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} @Min(value=10, message="年龄的最小值为10")
public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} }
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <mvc:annotation-driven/>
</beans>
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping; @Controller
public class UserController { @RequestMapping("login")
public String login(@Valid User user, BindingResult result) {
if (result.hasErrors())
return "user/login";
return "redirect:/";
} }

使用@NotBlank等注解,然后在要验证的地方使用@Valid 标签。最后验证的结果是在BindingResult 获取,注意据说result 要紧挨着前面的@Valid,而且是一个验证一个BindingResult参数。

2. 还有就是继承Validator 接口。