Action配置中一定要设置input返回页面
添加验证只要创建验证的xml文件
在Action同包下,创建:Action类名-validation.xml
如:ValidateAction创建ValidateAction-validation.xml
<!--每个方法单独配置一个Action -->
<!-- 在Action同包下,创建:Action类名-action方法配置名称-validation.xml-->
<action name="validateAdd" class="com.struts2.validator.ValidateAction" method="add">
<!-- 要创建ValidateAction-validateAdd-validation.xml-->
<!-- 使用通配符配置-->
<!-- 在Action同包下,创建:Action类名-action方法对应的名称-validation.xml-->
<action name="validate_*" class="com.struts2.validator.ValidateAction" method="{1}">
<!-- 要创建ValidateAction-validate_add-validation.xml,validate_add为访问这个action方法的路径-->
注意:
1.要验证的方法不能叫input.
2.这样配置在form表单中要在<s:form action="validate_add">中action写好名称,
不能写action="validate_",然后<s:submit value="提交"method="add" />
这样会找不到对应的配置文件,跳过验证.
3.如果验证出错,返回input页面时,那些存在ValueStack中的值会丢失,可以将Action实现Preparable接口,
然后prepare()方法里初始化添加页面需要的值.
4.如果使用Preparable接口,必须在action配置中添加<interceptor-ref name="paramsPrepareParamsStack" />.
这样prepare()才能得到form提交的参数.
<!DOCTYPEvalidators PUBLIC "-//OpenSymphonyGroup//XWork Validator 1.0.2//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<validators>
<!-- 要验证的字段名称 -->
<!-- 要验证Action中UserBean的id字段,name="userBean.id"(userBean为Action中的变量名)-->
<field name="mail">
<!-- type要验证的类型,short-circuit(默认false),true含义,如果当前验证失败了,下面的验证就不执行了.如requiredstring失败了,email就不验证了.-->
<!-- field-validator下面可以有多个param元素,但是最多只能有一个message-->
<field-validator type="requiredstring">
<param name="trim">true</param>
<message>Please enter a mail</message>
</field-validator>
<field-validator type="email">
<message>
Invalid MAIL
</message>
</field-validator>
</field>
</validators>
保证字段的值不是空值null.空字符串不是空值null.
<field name="userName">
<field-validator type="required">
<message>Please enter a user name</message>
</field-validator>
</field>
保证字段不是空值null,也不是空白(empty).
param:trim(boolean) ->true->去除前后空格
<field name="userName">
<field-validator type="requiredstring">
<param name="trim">true</param>
<message>Please enter a user name</message>
</field-validator>
</field>
<field name="password">
<field-validator type="requiredstring">
<param name="trim">false</param>
<message>Please enter a password</message>
</field-validator>
</field>
验证字段值是否可以转换为一个整数.
param: min(int);max(int)
<field name="yeaar">
<field-validator type="int">
<param name="min">1999</param>
<param name="max">2010</param>
<message>year:1999-2010</message>
</field-validator>
</field>
验证给定日期字段的值是否在一个给定的范围内.
param:max(date);min(date)
<field name="borthday">
<field-validator type="int">
<!-- 格式取决于当前地理时区 -->
<param name="min">1999-01-01</param>
<param name="max">2010-01-01</param>
<message>birthday:1999-2010</message>
</field-validator>
</field>
给定的String值是否是一个电子邮件地址
<field name="email">
<field-validator type="email">
<message>Invalid email</message>
</field-validator>
</field>
给定的String值是否是一个合法的URL(要有前缀)
<field name="url">
<field-validator type="url">
<message>Invalid URL</message>
</field-validator>
</field>
验证给定字段是否满足一个OGNL表达式.
区别:expression 不是一个字段验证程序,失败时将生成一个动作错误.(JSP中调用<s:actionerror/>才显示出错信息)
fieldexpression 是一个字段验证程序,失败时将抛出一个字段错误.(对字段验证)
param:expression(String)OGNL表达式
expression:
public class ExpressionTestAction {
//属性生成get,set
private int min;
private int max;
}
<validator type="expression">
<param name="expression">
max > min
</param>
<message>
Maximum temperature must begreater than Minimum temperature
</message>
</validator>
<!-- jsp -->
<s:actionerror/>
fieldexpression:
public class FieldExpressionTestAction {
//属性生成get,set
private int min;
private int max;
}
<!-- 对字段验证 -->
<field name="max">
<field-validator type="fieldexpression">
<param name="expression">
max > min
</param>
<message>
Maximum temperature must begreater than Minimum temperature
</message>
</field-validator>
</field>
把同一个验证程序配置文件用于多个动作(对一个Bean写验证文件,每个使用的Action只要引用)
//UserBean
public class UserBean {
//属性get,set
private String name;
private int age;
}
//UserBean-validation.xml(和UserBean放在同一个包中)
<field name="name">
<field-validator type="requiredstring">
<message>用户名必须</message>
</field-validator>
</field>
<field name="age">
<field-validator type="int">
<param name="min">18</param>
<paramname="max">99</param>
<message>Age must be between 18 and 99</message>
</field-validator>
</field>
//Action的validation.xml
<!-- userBean变量名 -->
<field name="userBean">
<field-validator type="visitor">
<!--message会和UserBean验证中的message一起显示 -->
<message>用户: </message>
</field-validator>
</field>
如果另一个Action对UserBean使用另一个标准的验证,可以创建新的验证文件
//UserBean-specific-validation.xml
<!-- 和之前的验证不同 -->
<field name="age">
<field-validator type="int">
<param name="min">30</param>
<paramname="max">50</param>
<message>Age must be between 30 and 50</message>
</field-validator>
</field>
//另一个Action的validation.xml
<field name="userBean">
<field-validator type="visitor">
<!-- xml中扩展的名字,执行UserBean-specific-validation.xml的验证 -->
<param name="context">specific</param>
<message>用户1: </message>
</field-validator>
</field>
检查对某个属性进行类型转换是否会导致一个转换错误
<field name="age">
<field-validator type="conversion">
<message>
An age must be an integer.
</message>
</field-validator>
</field>
验证一个非空的字段值是不是足够的长度
param:minLength(int);maxLength(int);trim(boolean)
<field name="password">
<field-validator type="requiredstring">
<param name="minLength">6</param>
<param name="maxLength">14</param>
<message>length:6-14</message>
</field-validator>
</field>
给定的值是否与一个给定的正则表达式匹配
param:expression(String)正则表达式;caseSensitive(boolean)是否区别大小写,默认为true;trim(boolean)是否去除前后空格
<field name="phone">
<field-validator type="regex">
<param name="expression">
<![CDATA[\d\d\d\-\d\d\d\-\d\d\d\d]]>
</param>
<message>
Invalid phone number orinvalid format
</message>
</field-validator>
</field>
利用Validateable接口实现验证,实现void validate()方法.
ActionSupport类已经实现了这个接口
//继承ActionSupport
public class User extends ActionSupport {
//属性get,set
private String userName;
private String password;
private static List<String> userNames = new ArrayList<String>();
static {
userNames.add("harry");
userNames.add("sally");
}
//验证方法
public void validate() {
if (userNames.contains(userName)) {
//添加出错信息
addFieldError("userName", "'" + userName + "' has been taken.");
}
}
}
要创建一个普通的验证程序(非字段验证程序),扩展ValidatorSupport类.验证失败要从validate方法调用addActionError方法.
要创建一个字段验证程序,扩展FieldValidatorSupport类.验证失败要从validate方法调用addFieldError方法.
如果要能接受参数,要在类中定义一个相应的属性,并生成get,set.
public class StrongPasswordValidator extends FieldValidatorSupport {
//属性
private int minLength = -1;
public void setMinLength(int minLength) {
this.minLength = minLength;
}
public int getMinLength() {
returnminLength;
}
//验证方法
public void validate(Object object) throws ValidationException {
StringfieldName = getFieldName();
Stringvalue = (String) getFieldValue(fieldName, object);
if (value == null || value.length() <= 0) {
// use a required validator for these
return;
}
if ((minLength > -1) && (value.length() < minLength)) {
addFieldError(fieldName, object);
} else if (!isPasswordStrong(value)) {
addFieldError(fieldName, object);
}
}
private static final String GROUP_1 = "abcdefghijklmnopqrstuvwxyz";
private static final String GROUP_2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final String GROUP_3 = "0123456789";
protected boolean isPasswordStrong(String password) {
boolean ok1 = false;
boolean ok2= false;
boolean ok3= false;
int length = password.length();
for (int i = 0; i < length; i++) {
if (ok1 && ok2 && ok3) {
break;
}
String character = password.substring(i, i + 1);
System.out.println("character:" + character);
if (GROUP_1.contains(character)) {
ok1 = true;
continue;
}
if (GROUP_2.contains(character)) {
ok2 = true;
continue;
}
if (GROUP_3.contains(character)) {
ok3 = true;
}
}
return (ok1 && ok2 && ok3);
}
}
在src下创建validators.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork ValidatorConfig 1.0//EN" "http://www.opensymphony.com/xwork/xwork-validator-config-1.0.dtd">
<validators>
<!-- 名称(type对应值),类路径 -->
<validator name="strongpassword" class="com.validator.StrongPasswordValidator"/>
</validators>
<field name="password">
<field-validator type="strongpassword">
<param name="minLength">8</param>
<message>
Password must be at least 8 characterslong
and contains at least onelower case character,
one upper case character, anda digit.
</message>
</field-validator>
</field>