Struts中的验证框架

我们要实现这个验证的话,

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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值