5月23日 西安 OSC 源創會開始報名啦,存儲、虛擬機、Docker 等乾貨分享java
1、基礎框架 SpringMVC-4.0.3.RELEASE,使用的maven來管理jar依賴web
2、依賴的jar,spring
1
2
3
4
5
|
<
dependency
>
<
groupId
>org.hibernate</
groupId
>
<
artifactId
>hibernate-validator</
artifactId
>
<
version
>5.0.2.Final</
version
>
</
dependency
>
|
上面是對Hibernate Validator 支持所須要的包,spring的jar省略。mvc
3、spring配置文件 applicationContext.xmlapp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
<
mvc:annotation-driven
validator
=
"validator"
/>
<!-- 如下 validator ConversionService 在使用 mvc:annotation-driven 會 自動註冊-->
<
bean
id
=
"validator"
class
=
"org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"
>
<
property
name
=
"providerClass"
value
=
"org.hibernate.validator.HibernateValidator"
/>
<!-- 若是不加默認到 使用classpath下的 ValidationMessages.properties -->
<
property
name
=
"validationMessageSource"
ref
=
"messageSource"
/>
</
bean
>
<!-- 國際化的消息資源文件(本系統中主要用於顯示/錯誤消息定製) -->
<
bean
id
=
"messageSource"
class
=
"org.springframework.context.support.ReloadableResourceBundleMessageSource"
>
<
property
name
=
"basenames"
>
<
list
>
<!-- 在web環境中必定要定位到classpath 不然默認到當前web應用下找 -->
<
value
>classpath:messages</
value
>
<
value
>classpath:org/hibernate/validator/ValidationMessages</
value
>
</
list
>
</
property
>
<
property
name
=
"useCodeAsDefaultMessage"
value
=
"false"
/>
<
property
name
=
"defaultEncoding"
value
=
"UTF-8"
/>
<
property
name
=
"cacheSeconds"
value
=
"60"
/>
</
bean
>
|
通過上面三步,就可讓SpringMVC支持hibernate Validator,能夠說整合已大功告成。如今看看具體使用框架
4、須要驗證的實體類maven
1
2
3
4
5
6
7
8
9
10
11
12
13
|
public
class
IssueMessageBO {
@NotNull
(message=
"{message.content.empty}"
)
// 將驗證消息寫在classpath下message.properties
@Size
(min =
2
, max =
140
,message=
"{message.content.length}"
)
private
String content;
//發佈內容
private
String qiniuImgInfo;
//七牛圖片信息
@NotNull
(message=
"{message.schoolIds.empty}"
)
private
String schoolIds;
//學校
private
int
publisherType;
//發佈者類型
private
boolean
hasTop;
//是否置頂
private
int
topDay;
//置頂的天數
....
}
|
JSR-303只是一個規範,而Spring也沒有對這一規範進行實現,那麼當咱們在SpringMVC中須要使用到JSR-303的時候就須要咱們提供一個對JSR-303規範的實現,Hibernate Validator是實現了這一規範的,這裏我將以它做爲JSR-303的實現來說解SpringMVC對JSR-303的支持。ide
JSR-303的校驗是基於註解的,它內部已經定義好了一系列的限制註解,咱們只須要把這些註解標記在須要驗證的實體類的屬性上或是其對應的get方法上.this
JSR-303原生支持的限制有以下幾種:spa
除了JSR-303原生支持的限制類型以外咱們還能夠定義本身的限制類型。定義本身的限制類型首先咱們得定義一個該種限制類型的註解,並且該註解須要使用@Constraint標註。
5、controller中的數據驗證
1
2
3
4
5
6
7
8
9
10
|
@RequestMapping
(value =
"/addMessage.action"
, method = RequestMethod.POST)
public
@ResponseBody
String addMessage(HttpServletRequest request, HttpServletResponse response,
@Valid
IssueMessageBO issueMessageBO,BindingResult result)
throws
IOException{
Result retVal = ValidatorResultHandler.handle(result);
if
(retVal.getStatus() == Const.FAILURE){
response.getWriter().write(JSON.toJSONString(retVal));
}
else
{
response.getWriter().write(JSON.toJSONString(treeholeMessageService.issueMessage(issueMessageBO)));
}
return
null
;
}
|
在 applicationContext.xml 加入了
1
|
<
mvc:annotation-driven
validator
=
"validator"
/>
|
Spring會自動檢測classpath下的JSR-303提供者並自動啓用對JSR-303的支持,把對應的校驗錯誤信息放到Spring的Errors對象中
而後我使用了 validatorResultHandler 類來處理驗證結果
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
public
class
ValidatorResultHandler {
public
static
Result handle(BindingResult result){
Result retVal =
new
Result();
if
(result.hasErrors()){
List<ObjectError> list = result.getAllErrors();
ObjectError oe = list.get(
0
);
retVal.setMessage(oe.getDefaultMessage());
}
else
{
retVal.setStatus(Const.SUCCESS);
}
return
retVal;
}
}
|
這樣處理就完成了。
6、有的時候,咱們對一個實體類須要有多中驗證方式,在不一樣的狀況下使用不一樣驗證方式,好比說對於一個實體類來的id來講,保存的時候是不須要的,對於更新時是必須的,能夠以下配置:
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
|
public
class
UserModel {
private
int
id;
private
String username;
private
String content;
@NotNull
(message=
"{id.empty}"
,groups={First.
class
})
public
int
getId() {
return
id;
}
public
void
setId(
int
id) {
this
.id = id;
}
@NotNull
(message=
"{username.empty}"
,groups = {First.
class
, Second.
class
})
public
String getUsername() {
return
username;
}
public
void
setUsername(String username) {
this
.username = username;
}
@NotNull
(message=
"{content.empty}"
,groups = {First.
class
, Second.
class
})
public
String getContent() {
return
content;
}
public
void
setContent(String content) {
this
.content = content;
}
}
|
經過 groups 對驗證進行分組
在controler中的代碼以下
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
|
@RequestMapping
(value =
"/save.action"
, method = RequestMethod.POST)
public
@ResponseBody
String save(HttpServletRequest request, HttpServletResponse response,
@Validated
({ Second.
class
}) UserModel userModel,BindingResult result)
throws
IOException{
response.setCharacterEncoding(
"utf-8"
);
System.out.println(
"----"
+userModel.getUsername());
if
(result.hasErrors()){
List<ObjectError> list = result.getAllErrors();
for
(ObjectError objectError:list){
System.out.println(objectError.getDefaultMessage());
}
response.getWriter().write(JSON.toJSONString(list));
return
null
;
}
response.getWriter().write(
"rrrrrr"
);
return
null
;
}
@RequestMapping
(value =
"/update.action"
, method = RequestMethod.POST)
public
@ResponseBody
String update(HttpServletRequest request, HttpServletResponse response,
@Validated
({First.
class
, Second.
class
}) UserModel user,BindingResult result)
throws
IOException{
response.setCharacterEncoding(
"utf-8"
);
if
(result.hasErrors()){
List<ObjectError> list = result.getAllErrors();
for
(ObjectError objectError:list){
System.out.println(objectError);
}
response.getWriter().write(JSON.toJSONString(list));
return
null
;
}
response.getWriter().write(
"rrrrrr"
);
return
null
;
}
|