使用动态FormBean与struts验证框架
第一步,安装插件,在struts-config.xml中配置
[code]<message-resources parameter="ApplicationResources" />
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEBINF/validation.xml" />
</plug-in>[/code]
validator-rules.xml是struts自带的,validation.xml须要自已新建
第二步,将validator-rules.xml中以下代码
[code]#------------------------ERROR-----------------
errors.required={0} is required.
errors.minlength={0} can not be less than {1} characters.
errors.maxlength={0} can not be greater than {1} characters.
errors.invalid={0} is invalid.
errors.byte={0} must be a byte.
errors.short={0} must be a short.
errors.integer={0} must be an integer.
errors.long={0} must be a long.
errors.float={0} must be a float.
errors.double={0} must be a double.
errors.date={0} is not a date.
errors.range={0} is not in the range {1} through {2}.
errors.creditcard={0} is an invalid credit card number.
errors.email={0} is an invalid e-mail address.[/code]
拷贝到ApplicationResources.properties中,为了支持国际化ApplicationResources.properties同目录下新建ApplicationResources_zh_CN.properties需注意的是中文内容需通过native2ascii.exe进行转换。
命令使用格式:native2ascii 原文件 目标文件
我自已的常用做法是在JDK的ben目录下建一个.bat文件
内容:
cd %java_home%/bin/
native2ascii ApplicationResources_chinese.properties ApplicationResources_zh_CN.properties
如:ApplicationResources_chinese.properties中的文本:
errors.invalid={0} 无效.
errors.required={0} 不能为空.
转换后ApplicationResources_zh_CN.properties中的文本:
errors.required={0} \u4e0d\u80fd\u4e3a\u7a7a.
errors.invalid={0} \u65e0\u6548.
第三步,新建formBean与action
[code]<!--使用动态的验证表单-->
<form-bean name="regForm"
type="org.apache.struts.validator.DynaValidatorForm">
<form-property name="username" type="java.lang.String" />
<form-property name="password" type="java.lang.String" />
<form-property name="password2" type="java.lang.String" />
</form-bean>
......
<!--需注意得是validate属性必须为true-->
<action attribute="regForm" name="regForm" parameter="method"
path="/userReg" scope="request" input="/view/user/regedit.jsp"
type="org.springframework.web.struts.DelegatingActionProxy"
validate="true">
<forward name="regFail" path="/view/user/regedit.jsp" redirect="false" />
<forward name="regSuccess" path="/view/user/login.jsp" redirect="false" />
</action>[/code]
第四步,在validator.xml中定义验证规则
struts自带一些验证规则可供使用:
Byte、CreditCard、Date、Double、Email、Float、Integer、Long、Mask、MinLength、MaxLength、Range、Required、Short
通过field元素的depends属性指定依赖
当然struts也提供了自定义验证类的使用:
如验证密码一致性,编写以下类(引自struts中的例子)
[code]package com.note.validator;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.validator.Field;
import org.apache.commons.validator.GenericValidator;
import org.apache.commons.validator.ValidatorAction;
import org.apache.commons.validator.ValidatorUtil;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.validator.Resources;
public class CustomValidator {
public CustomValidator() {
super();
}
/**
* 功能:验证密码一致性(函数名必须以validate开头)
* @param bean
* @param va
* @param field
* @param errors
* @param request
* @return
*/
public static boolean validateTwoFields(Object bean, ValidatorAction va,
Field field, ActionErrors errors, HttpServletRequest request) {
String value = ValidatorUtil
.getValueAsString(bean, field.getProperty());
String sProperty2 = field.getVarValue("secondProperty");
String value2 = ValidatorUtil.getValueAsString(bean, sProperty2);
if (!GenericValidator.isBlankOrNull(value)) {
try {
if (!value.equals(value2)) {
errors.add(field.getKey(), Resources.getActionError(
request, va, field));
return false;
}
} catch (Exception e) {
errors.add(field.getKey(), Resources.getActionError(request,
va, field));
return false;
}
}
return true;
}
}[/code]
validator.xml文件示例
[code]<form-validation>
<global>
<!-- 自定义验证器 -->
<validator name="twoFields"
classname="com.note.validator.CustomValidator"
method="validateTwoFields"
methodParams="java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionErrors,
javax.servlet.http.HttpServletRequest"
msg="errors.twofields" />
<!-- 自定义验证器 -->
<!-- 全局常量 -->
<constant>
<constant-name>string6_20</constant-name>
<!--正则表达式-->
<constant-value>^\w{6,20}$</constant-value>
</constant>
<!-- 全局常量 -->
</global>
<formset>
<!-- 注册表单验证 -->
<form name="regForm">
<field property="username" depends="required,mask">
<!--resource为true时将去ApplicationResources中查找对应key的值-->
<arg0 key="lable.username" resource="true" />
<var>
<var-name>mask</var-name>
<var-value>${string6_20}</var-value>
</var>
</field>
<field property="password"
depends="required,mask,twoFields">
<arg0 key="lable.password" resource="true" />
<var>
<var-name>mask</var-name>
<var-value>${string6_20}</var-value>
</var>
<var>
<var-name>secondProperty</var-name>
<var-value>password2</var-value>
</var>
</field>
</form>
</formset>
</form-validation>[/code]
第五步,结合action一起使用
[code] /**
* 功能:新用户注册
*
* @param mapping
* @param form
* @param request
* @param response
* @return
*/
public ActionForward regedit(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
DynaActionForm regForm = (DynaActionForm) form;
String username = (String) regForm.get("username");
String password = (String) regForm.get("password");
Users user = this.ius.getUserByName(username);
ActionErrors errors = new ActionErrors();
if (user == null) {
user = new Users();
user.setUsername(username);
user.setPassword(password);
user.setLevel(0);
user.setAddtime(new java.util.Date());
user.setLastime(new java.util.Date());
this.ius.addUser(user);
} else {
errors.add("username", new ActionError("errors.username.exist"));
this.saveErrors(request, errors);
return mapping.findForward("regFail");
}
return mapping.findForward("regSuccess");
}[/code]
到此为止,struts验证框架的使用基本完成。
第一步,安装插件,在struts-config.xml中配置
[code]<message-resources parameter="ApplicationResources" />
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEBINF/validation.xml" />
</plug-in>[/code]
validator-rules.xml是struts自带的,validation.xml须要自已新建
第二步,将validator-rules.xml中以下代码
[code]#------------------------ERROR-----------------
errors.required={0} is required.
errors.minlength={0} can not be less than {1} characters.
errors.maxlength={0} can not be greater than {1} characters.
errors.invalid={0} is invalid.
errors.byte={0} must be a byte.
errors.short={0} must be a short.
errors.integer={0} must be an integer.
errors.long={0} must be a long.
errors.float={0} must be a float.
errors.double={0} must be a double.
errors.date={0} is not a date.
errors.range={0} is not in the range {1} through {2}.
errors.creditcard={0} is an invalid credit card number.
errors.email={0} is an invalid e-mail address.[/code]
拷贝到ApplicationResources.properties中,为了支持国际化ApplicationResources.properties同目录下新建ApplicationResources_zh_CN.properties需注意的是中文内容需通过native2ascii.exe进行转换。
命令使用格式:native2ascii 原文件 目标文件
我自已的常用做法是在JDK的ben目录下建一个.bat文件
内容:
cd %java_home%/bin/
native2ascii ApplicationResources_chinese.properties ApplicationResources_zh_CN.properties
如:ApplicationResources_chinese.properties中的文本:
errors.invalid={0} 无效.
errors.required={0} 不能为空.
转换后ApplicationResources_zh_CN.properties中的文本:
errors.required={0} \u4e0d\u80fd\u4e3a\u7a7a.
errors.invalid={0} \u65e0\u6548.
第三步,新建formBean与action
[code]<!--使用动态的验证表单-->
<form-bean name="regForm"
type="org.apache.struts.validator.DynaValidatorForm">
<form-property name="username" type="java.lang.String" />
<form-property name="password" type="java.lang.String" />
<form-property name="password2" type="java.lang.String" />
</form-bean>
......
<!--需注意得是validate属性必须为true-->
<action attribute="regForm" name="regForm" parameter="method"
path="/userReg" scope="request" input="/view/user/regedit.jsp"
type="org.springframework.web.struts.DelegatingActionProxy"
validate="true">
<forward name="regFail" path="/view/user/regedit.jsp" redirect="false" />
<forward name="regSuccess" path="/view/user/login.jsp" redirect="false" />
</action>[/code]
第四步,在validator.xml中定义验证规则
struts自带一些验证规则可供使用:
Byte、CreditCard、Date、Double、Email、Float、Integer、Long、Mask、MinLength、MaxLength、Range、Required、Short
通过field元素的depends属性指定依赖
当然struts也提供了自定义验证类的使用:
如验证密码一致性,编写以下类(引自struts中的例子)
[code]package com.note.validator;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.validator.Field;
import org.apache.commons.validator.GenericValidator;
import org.apache.commons.validator.ValidatorAction;
import org.apache.commons.validator.ValidatorUtil;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.validator.Resources;
public class CustomValidator {
public CustomValidator() {
super();
}
/**
* 功能:验证密码一致性(函数名必须以validate开头)
* @param bean
* @param va
* @param field
* @param errors
* @param request
* @return
*/
public static boolean validateTwoFields(Object bean, ValidatorAction va,
Field field, ActionErrors errors, HttpServletRequest request) {
String value = ValidatorUtil
.getValueAsString(bean, field.getProperty());
String sProperty2 = field.getVarValue("secondProperty");
String value2 = ValidatorUtil.getValueAsString(bean, sProperty2);
if (!GenericValidator.isBlankOrNull(value)) {
try {
if (!value.equals(value2)) {
errors.add(field.getKey(), Resources.getActionError(
request, va, field));
return false;
}
} catch (Exception e) {
errors.add(field.getKey(), Resources.getActionError(request,
va, field));
return false;
}
}
return true;
}
}[/code]
validator.xml文件示例
[code]<form-validation>
<global>
<!-- 自定义验证器 -->
<validator name="twoFields"
classname="com.note.validator.CustomValidator"
method="validateTwoFields"
methodParams="java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionErrors,
javax.servlet.http.HttpServletRequest"
msg="errors.twofields" />
<!-- 自定义验证器 -->
<!-- 全局常量 -->
<constant>
<constant-name>string6_20</constant-name>
<!--正则表达式-->
<constant-value>^\w{6,20}$</constant-value>
</constant>
<!-- 全局常量 -->
</global>
<formset>
<!-- 注册表单验证 -->
<form name="regForm">
<field property="username" depends="required,mask">
<!--resource为true时将去ApplicationResources中查找对应key的值-->
<arg0 key="lable.username" resource="true" />
<var>
<var-name>mask</var-name>
<var-value>${string6_20}</var-value>
</var>
</field>
<field property="password"
depends="required,mask,twoFields">
<arg0 key="lable.password" resource="true" />
<var>
<var-name>mask</var-name>
<var-value>${string6_20}</var-value>
</var>
<var>
<var-name>secondProperty</var-name>
<var-value>password2</var-value>
</var>
</field>
</form>
</formset>
</form-validation>[/code]
第五步,结合action一起使用
[code] /**
* 功能:新用户注册
*
* @param mapping
* @param form
* @param request
* @param response
* @return
*/
public ActionForward regedit(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
DynaActionForm regForm = (DynaActionForm) form;
String username = (String) regForm.get("username");
String password = (String) regForm.get("password");
Users user = this.ius.getUserByName(username);
ActionErrors errors = new ActionErrors();
if (user == null) {
user = new Users();
user.setUsername(username);
user.setPassword(password);
user.setLevel(0);
user.setAddtime(new java.util.Date());
user.setLastime(new java.util.Date());
this.ius.addUser(user);
} else {
errors.add("username", new ActionError("errors.username.exist"));
this.saveErrors(request, errors);
return mapping.findForward("regFail");
}
return mapping.findForward("regSuccess");
}[/code]
到此为止,struts验证框架的使用基本完成。