Spring MVC 提供了两种数据校验的方式:
1、基于 Validator 接口。
2、使用 Annotation JSR - 303 标准进行校验。
基于 Validator 接口的⽅式需要自定义 Validator 验证器,每⼀条数据的验证规则需要开发者⼿动完成, 使⽤ Annotation JSR - 303 标准则不需要⾃定义验证器,通过注解的方式可以直接在实体类中添加每个属性的验证规则,这种方式更加方便,实际开发中推荐使用。
1.定义实体类Account
1
2
3
4
5
6
7
|
package entity;
import lombok.Data;
@Data
public class Account {
private String name;
private String password;
}
|
2.自定义验证器 AccountValidator,实现 Validator 接口
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
package validator;
import entity.Account;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
public class AccountValidator implements Validator {
@Override
public boolean supports(Class<?> aClass) {
return Account. class .equals(aClass);
}
@Override
public void validate(Object o, Errors errors) {
ValidationUtils.rejectIfEmpty(errors, "name" , null , "姓名不能为空" );
ValidationUtils.rejectIfEmpty(errors, "password" , null , "密码不能为空" );
}
}
|
Validator中有两个方法, supports是判断传入是否为目标类,如果是的话则进行下一步,数据验证的操作。
3.控制器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
package Mycontroller;
import entity.Account;
import entity.Person;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.validation.Valid;
@Controller
@RequestMapping ( "/validator" )
public class ValidatorHandler {
@GetMapping ( "/login" )
public String login(Model model){
model.addAttribute( "account" , new Account());
return "login" ;
}
@PostMapping ( "/login" )
public String login( @Validated Account account, BindingResult bindingResult){
if (bindingResult.hasErrors()){
return "login" ;
}
return "index" ;
}
|
4. springmvc.xml 配置验证器
1
2
3
|
< bean id = "accountValidator" class = "com.southwind.validator.AccountValidator" >
</ bean >
< mvc:annotation-driven validator = "accountValidator" ></ mvc:annotation-driven >
|
5.jsp文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<%@ page contentType= "text/html;charset=UTF-8" language= "java" %>
<%@ page isELIgnored= "false" %>
<%@ taglib prefix= "form" uri= "http://www.springframework.org/tags/form" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form:form modelAttribute= "account" action= "/validator/login" method= "post" >
姓名:<form:input path= "name" ></form:input><form:errors path= "name" ></form:errors><br>
密码:<form:input path= "password" ></form:input><form:errors path= "password" ></form:errors><br>
<input type= "submit" value= "登录" >
</form:form>
</body>
</html>
|
以上就是java开发之基于Validator接口的SpringMVC数据校验方式的详细内容,更多关于SpringMVC数据校验的资料请关注服务器之家其它相关文章!
原文链接:https://blog.csdn.net/DrLai/article/details/119577797