使用initbinder做验证的情况一般会在此controller中提交的数据需要有一些是业务性质的,也即比较复杂的验证情况下才会使用。大部份简单的表单验证,使用annotation验证即可以解决。
annotation验证使用方法可参见:http://www.zzvips.com/article/155119.html
这里需要注意的一点:initbinder和annotation两种验证只能二选一,如果使用了initbinder,就不能使用annotation验证。
前面的web.xml和spring.xml的配置就不再重复,可参见上面链接中的配置。一模一样。
直接上代码:
1、user5 model实体类
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
package com.my.controller.bean;
import java.util.date;
public class user5 {
private long id;
private string name;
private string password;
private date createtime;
private int age;
public long getid() {
return id;
}
public void setid( long id) {
this .id = id;
}
public string getname() {
return name;
}
public void setname(string name) {
this .name = name;
}
public string getpassword() {
return password;
}
public void setpassword(string password) {
this .password = password;
}
public date getcreatetime() {
return createtime;
}
public void setcreatetime(date createtime) {
this .createtime = createtime;
}
public int getage() {
return age;
}
public void setage( int age) {
this .age = age;
}
}
|
2、新增一个validator:
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
|
package com.my.controller.validator;
import org.springframework.stereotype.component;
import org.springframework.validation.errors;
import org.springframework.validation.validationutils;
import org.springframework.validation.validator;
import com.my.controller.bean.user5;
@component
public class testvalidator implements validator {
@override
public boolean supports( class <?> paramclass) {
return user5. class .equals(paramclass);
}
@override
public void validate(object obj, errors errors) {
user5 user = (user5) obj;
validationutils.rejectifemptyorwhitespace(errors, "name" , "valid.name" , null , "" );
if (user.getage() < 18 ) {
errors.rejectvalue( "age" , "valid.agemin" , new object[]{ "age" , 18 }, "年龄不能小于{1}岁" );
}
}
}
|
这里需要加入@component,注入di
3、controller
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
package com.my.controller;
import java.util.linkedhashmap;
import java.util.list;
import java.util.map;
import javax.validation.valid;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.beans.factory.annotation.qualifier;
import org.springframework.stereotype.controller;
import org.springframework.validation.bindingresult;
import org.springframework.validation.fielderror;
import org.springframework.validation.validator;
import org.springframework.web.bind.webdatabinder;
import org.springframework.web.bind.annotation.initbinder;
import org.springframework.web.bind.annotation.modelattribute;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestmethod;
import org.springframework.web.servlet.modelandview;
import com.my.controller.bean.user5;
@controller
@requestmapping (value= "binder" )
public class testinitbindercontroller {
@autowired
@qualifier (value= "testvalidator" )
private validator validator;
@initbinder
private void initbinder(webdatabinder binder) {
binder.setvalidator(validator);
}
@requestmapping (method=requestmethod.get)
public string index() {
return "/testinitbinder/index" ;
}
@requestmapping (value= "add" , method=requestmethod.post)
public modelandview add( @modelattribute @valid user5 user, bindingresult result) {
modelandview view = new modelandview( "testinitbinder/index" );
view.addobject( "user" , user);
if (result.haserrors()) {
list<fielderror> errs = result.getfielderrors();
map<string, string> maperrors = new linkedhashmap<string, string>();
for (fielderror err : errs) {
system.out.println( "objectname:" + err.getobjectname() + "\tfieldname:" + err.getfield()
+ "\tfieldvalue:" + err.getrejectedvalue() + "\tmessage:" + err.getdefaultmessage());
maperrors.put(err.getfield(), err.getdefaultmessage());
view.addobject( "errors" , maperrors);
}
return view;
}
return view;
}
}
|
把validator注入到controller中。
事实上,使用initbinder,在add controller中的err.getdefaultmessage()方法是取不到对应正确的message的。可以看最后的输入打印结果。
4、view
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
<%@ page language= "java" contenttype= "text/html; charset=utf-8" pageencoding= "utf-8" %>
<%@ taglib uri= "http://java.sun.com/jsp/jstl/core" prefix= "c" %>
<%@ taglib uri= "http://java.sun.com/jsp/jstl/fmt" prefix= "fmt" %>
<%@ taglib uri= "http://java.sun.com/jsp/jstl/functions" prefix= "fn" %>
<%@ taglib prefix= "st" uri= "http://www.springframework.org/tags" %>
<%@ taglib prefix= "form" uri= "http://www.springframework.org/tags/form" %>
<!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd" >
<html>
<head>
<meta http-equiv= "content-type" content= "text/html; charset=utf-8" >
<title>init binder</title>
</head>
<body>
<form:form action= "/testspringmvc1/binder/add" method= "post" modelattribute= "user5" >
user name:<input type= "text" id= "name" name= "name" value= "${user.name}" /><br/>
password:<input type= "text" id= "password" name= "password" value= "${user.password}" /><br/>
age:<input type= "text" id= "age" name= "age" value= "${user.age}" /><br/>
<input type= "submit" value= "add" />
<hr/>
error:<br/>
<form:errors path= "*" ></form:errors>
</form:form>
</body>
</html>
|
注意,这里只能使用<form:errors />来取得错误信息,且,这个<form:errors/>一定要在<form:form/>当中。
5、结果测试
点击add button:
打印输出:
可以看到,这里取不到错误的正确信息
事实上,在一个非常复杂表单页面,里头所提交的数据验证有一定的业务逻辑性时,initbinder应该都不多用,因为很多时候我们可以使用一个map,把errors插入进去,在页面读取即可。比如:
map<string, string> errors;
errors.add("name", "user name can not be empty!");
:
:
页面中只需要使用:
1
|
<span style= "color:red;" >${errors.name}<span>
|
即可。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://www.cnblogs.com/HD/p/4123686.html