我们要实现这个验证的话,
1.我们的Action需要继承ActionSupport 这个类,然后重写validate这个方法,或者写一个validateXxx方法。
重写validate()这个方法,是在调用每个处理方法之前都会调用这个validate()方法进行验证,而写一个validateXxx()方法是针对Xxx()方法之前才调用。
例如:
/**
* 转账
*/
public String transfer()
{
//获取账户
String[] accountNos = account.getAccountNo().split(",");
String acc1=accountNos[0].trim();
String acc2=accountNos[1].trim();
Account a1=new Account();
a1.setAccountNo(acc1);
Account a2=new Account();
a2.setAccountNo(acc2);
accountService.transfer(a1, a2,account.getBalance());
return NONE;
}
/**
* 转账验证
*/
public void validateTransfer()
{
//获取账户
String[] accountNos = account.getAccountNo().split(",");
int i=0;
boolean b=true;
//判断账户是否为空
for (String accountNo : accountNos)
{
i++;
if("".equals(accountNo.trim())||null==accountNo)
{
b=false;
this.addFieldError("accountNo", "账户"+i+"不能为空!");
}
}
//判断账户是否存在
if(b)
{
int a=0;
for (String accountNo : accountNos)
{
a++;
List acc = accountService.getAccount(accountNo.trim());
if(acc==null||acc.size()==0)
this.addFieldError("accountNo", "账户"+a+"不存在!");
}
}
super.validate();
}
2.在前台页面需要引入s标签,并且加入<s:fielderror /> 标签。
例如:
<form action="account_transfer">
<s:token />
<s:fielderror />
<h2>转账</h2>
账户1<input type="text" name="accountNo" />
向账户2<input type="text" name="accountNo" />打款
<input type="text" name="balance" />元<br />
<input type="submit" value="转账" />
</form>
3.在struts.xml中的配置中也需要加入一个"input" 的逻辑视图名
例如:
<action name="account_*" class="com.zxxz.action.AccountAction" method="{1}">
<interceptor-ref name="myStack" />
<result name="input">/account/zhuanzhang.jsp</result>
</action>