posts - 15,comments - 0,trackbacks - 0

FormBean的验证:

1、重写FormBean的validate方法。

public ActionErrors validate(ActionMapping mapping,  HttpServletRequest request) {
  // TODO Auto-generated method stub
  ActionErrors errors = new ActionErrors();
  if (name == null || name.equals("")) { //nameEmpty为错误信息名
   errors.add("nameEmpty", new ActionMessage("empty.error", "UserName"));
  }
  if (pwd == null || pwd.equals("")) {
   errors.add("pwdEmpty", new ActionMessage("empty.error", "PassWord"));
  } //empty.error定义在login.properties文件中,其value值为{0} must not be empty!所以empty.error后面会有UserName和PassWord。
  return errors;
 }
2、在struts-config.xml中配置action节点的validate与input属性,validate表示是否调formBean的validate方法,input是如果出错的话跳转的错误处理界面。注意:如果formBean重写的了validate方法并且action节点validate属性为true,那一定要添加input属性。  

3、在struts-config.xml中添加<message-resources parameter="org.koyo.views.login" />注意:其中的parameter属性的值是login.properties文件的路径。(容易被漏掉,多加注意)

4、在界面使用<html:errors />或<html:errors property="nameEmpty"/>显示错误信息。

步骤2、3、4,尤其是步骤3,经常会漏掉,应多加注意!!!

ActionBean的验证

1、在ActionBean中添加代码。

ActionMessages messages = new ActionMessages();//不要与FormBean混淆,此处直接就是ActionMessage
   messages.add("inputError", new ActionMessage("input.error"));
   super.saveErrors(request, messages);//此句容易被漏掉,且常会被错写成super.saveMessage(request,messages);
   return mapping.getInputForward();

步骤2、3、4,与FormBean验证相同。

主要区别:ActionBean验证主要做业务,需要与数据库交互,比如用户名是否可用,转账余额是否可用,出货余额等验证;formBean虽然完成客户端验证功能,但需要与服务器交互。注意不同的区分标准。。

 

本文章大部分内容转载自 西安云工厂http://www.xaygc.com/struts.html

posted on 2011-06-03 21:43 aya000 阅读(245) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: