Struts 2 - 重用自定义表达式验证器 [英] Struts 2 - reusing Custom Expression Validator
问题描述
在struts 2中,我们可以开发 @CustomValidator
,可以在应用程序范围内使用
In struts 2 we can develop @CustomValidator
which can be used in application wide
@CustomValidator(type = "CustomerNumberValidator", fieldName = "customerNo")
For验证超过一个字段我们使用 @ExpressionValidator
For validation MORE THAN ONE FIELD we use @ExpressionValidator
@ExpressionValidator(expression =
"( (!''.equals(account.firstName) && (!''.equals(account.lastName) )
|| (presonalAccount == false)",
key = "validate.account.name")
如果表达式过于复杂且需要我们使用OGNL来调用静态方法。静态方法将执行验证并返回 boolean
例如
If the expression is too complicated and needs to work on MORE THAN ONE FIELD we use OGNL to call static method. The static method will do the validation and return a boolean
for example
@ExpressionValidator(expression = "@foo.bar.CalendarUtil@compareDates(fromDate,toDate)", key = "validate.date.before")
以上是一些自定义表达式验证器!
我们在应用程序范围内使用 @ foo.bar.CalendarUtil @ compareDates
为我们进行此验证。
Above is some how a Custom Expression Validator !
And we use @foo.bar.CalendarUtil@compareDates
in application wide to make this validation for us.
是否有其他方法可以让我们使用自定义宽验证器?!是否有任何可以添加到struts的自定义表达式验证器,我们可以按照我们使用的方式调用它 @CustomValidator
Is there another approach which enables us to use a custom wide validator?! Is there any custom expression validator which can be added to struts and we can call it in action in the way we use @CustomValidator
推荐答案
创建自定义验证器(不与字段相关):
Create a Custom Validator (not field related):
public final class CompareDatesValidator extends ValidatorSupport {
private String fromDate; // getter and setter
private String toDate; // getter and setter
@Override
public void validate(Object o) throws ValidationException {
Date d1 = (Date)parse(fromDate, Date.class);
Date d2 = (Date)parse(toDate, Date.class);
if (d1==null || d2==null || d2.before(d1)){
addActionError(getDefaultMessage());
}
}
}
在<\\ n>中注册自定义验证器code> validators.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC
"-//OpenSymphony Group//XWork Validator Config 1.0//EN"
"http://www.opensymphony.com/xwork/xwork-validator-config-1.0.dtd">
<validators>
<validator name="compareDatesValidator"
class="org.foo.bar.CompareDatesValidator"/>
</validators>
在操作中使用验证器:
private Date startDate; // getter and setter
private Date endDate; // getter and setter
@Validations(
customValidators={
@CustomValidator(type="compareDatesValidator",
message="Dates provided are not valid."
parameters={
@ValidationParameter(name="fromDate", value="${startDate}"),
@ValidationParameter(name="toDate", value="${endDate}")})})
public String execute(){
return SUCCESS;
}
这篇关于Struts 2 - 重用自定义表达式验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!