分类:
2008-09-12 09:14:57
在Struts2中最简单的验证数据的方法是使用validate.我们从ActionSupport类的源代码中可以看到,ActionSupport类实现了一个Validateable接口。这个接口只有一个validate方法。如果Action类实现了这个接口,Struts2在调用execute方法之前首先会调用这个方法,我们可以在validate方法中验证,如果发生错误,可以根据错误的level选择字段级错误,还是动作级错误。并且可使用addFieldError或addActionError加入相应的错误信息,如果存在Action或Field错误,Struts2会返回“input”(这个并不用开发人员写,由Struts2自动返回),如果返回了“input”,Struts2就不会再调用execute方法了。如果不存在错误信息,Struts2在最后会调用execute方法。
这两个add方法和ActionErrors类中的add方法类似,只是add方法的错误信息需要一个ActionMessage对象,比较麻烦。除了加入错误信息外,还可以使用addActionMessage方法加入成功提交后的信息。当提交成功后,可以显示这些信息。
以上三个add方法都在ValidationAware接口中定义,并且在ActionSupport类中有一个默认的实现。其实,在ActionSupport类中的实现实际上是调用了ValidationAwareSupport中的相应的方法,也就是这三个add方法是在ValidationAwareSupport类中实现的,代码如下:
private final ValidationAwareSupport validationAware = new ValidationAwareSupport();
|
下面我们来实现一个简单的验证程序,来体验一个validate方法的使用。
先来在Web根目录建立一个主页面(validate.jsp),代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%> head> 输入内容: s:form> body> html> |
在上面的代码中,使用了Struts2的tag:、和,分别用来显示动作错误信息,字段错误信息,和动作信息。如果信息为空,则不显示。 现在我们来实现一个动作类,代码如下:
package action; |
[1]