可以的用<logic:MessagesNotPresent > 啊

解决方案 »

  1.   

    <logic:MessagesPresent > 和<logic:MessagesNotPresent > 可判断是否在request范围内存在指定的
    ActionMessages或其子类ActionErrors对象,以及在ActionMessages对象中是否存在特定的消息。有如下属性:
    name,message和property
      

  2.   

    下面是以前有人问过的问题,与本例类似:struts系列问题1: validator例子中为什么不用html:errors
    在第一个验证例子中,registration.jsp有这样一段:
    <logic:messagesPresent> 
       <bean:message key="errors.header"/>
       <ul>
       <html:messages id="error">
          <li><bean:write name="error"/></li>
       </html:messages>
       </ul><hr>
    </logic:messagesPresent>根据文档logic:messagesPresent缺省在request中查询Globals.ERROR_KEY属性.
    <html:errors>应该也可以达到同样效果,样式在四个errors.xxx中定义.为什么不简化它呢?另外,很多录入画面在提交有错误时,只出现有错误的栏位,在Struts中可以做到这种效果吗?同时用<html:errors/>和<logic:messagesPresent> ,即如下:
    <html:errors/>
    <logic:messagesPresent> 
       <bean:message key="errors.header"/>
       <ul>
       <html:messages id="error">
          <li><bean:write name="error"/></li>
       </html:messages>
       </ul><hr>
    </logic:messagesPresent>------------
    运行结果是:
    Validation Error
    You must correct the following error(s) before proceeding: First Name can not be less than 5 characters. Last Name is required. Address is required. City is required. State is required. Zip is required. E-mail is required. 
    Validation Error
    You must correct the following error(s) before proceeding: 
    First Name can not be less than 5 characters. 
    Last Name is required. 
    Address is required. 
    City is required. 
    State is required. 
    Zip is required. 
    E-mail is required. ----------------------------
    可见,采用<html:errors/>时是把所有出错信息简单连在一起显示,而后者是一个信息一个信息地提出来显示,可自由定义每个出错信息的显示方式,上述方式是换行,当前也还可在中间加入别的信息。当然,如果只有一个出借信息,那么上述两者的显示结果是一样的。**************
    更重要的一点是,出错信息是采用了setAttribute()函数来保存数据的,所以可以采用各种带有getAttribute()函数来显示,可见出错信息用<logic:Iterate>来提取也是一样的。
    可见,在Action、ActionForm、自定义标签文件或其它类文件中也可以直接用setAttribute()函数来保存出错数据。
      

  3.   

    kui说的很透彻,其实如果想使用<html:errors/>实现每次只显示一个错误也很简单。ActionForm中的Validate 方法里发现错误就返回errors就行。
       public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
          ActionErrors errors = new ActionErrors();
          HttpSession session = request.getSession(true);
        //  System.out.println(session.getAttribute("rand"));
        if ((username.trim().length() < 1) || (username.trim().length() > 12)){
            errors.add("userName", new ActionError("error.missing.userName"));
            return errors;
        }
          if ((password==null) || (password.trim().length() < 1) || !(password.equals(password2))){
            errors.add("password", new ActionError("error.missing.password"));
             return errors;
          }
         }
          return errors;
        }
      

  4.   

    但是并不能返回很多错误但是显示的时候只显示一个吧,如果这样我得做法就是在ActionForm里面做验证,Action直接获得错误信息返回就好了,这个不是更麻烦?
      

  5.   

    struts的本意是在ActionForm里做表单的输入格式验证。一些逻辑错误的验证做到逻辑操作中,最后通过Action截获错误返回。2者搭配使用,层次分明便于维护。