Struts1 中的 <logic:messagesPresent> 标记未循环处理操作消息中的多个错误

<logic:messagesPresent> tag in Struts1 not looping through multiple errors in Action Messages

我的 bean 中有一个字段未通过 2 次验证,因此使用以下命令在 ActionMessages 中插入了 2 条消息:

validationErrors.add("field1", new ActionMessage("Phone number is greater than 10 digits", false));
validationErrors.add("field1", new ActionMessage("Phone number has invalid characters", false));

虽然我在 ActionMessages 对象中看到错误(通过在调试器中设置断点),但只有第一个错误显示在我的 JSP 中,我有:

<logic:messagesPresent message="true">
    <html:messages id="message" property="field1" message="true">
        <logic:present name="message">
            <c:out value="${message}"/>
        </logic:present>
    </html:messages>
</logic:messagesPresent>

为什么只显示第一条消息,而 <html:messages> 应该遍历 属性 为 "field1" 的所有消息?

Struts <logic:messagesPresent> tag 检查消息是否存在于当前请求中。

消息在请求中的关键字 Globals.MESSAGE_KEY 下找到。如果您使用属性 message,则只检查消息。

By default the tag will retrieve the request scope bean it will iterate over from the Globals.ERROR_KEY constant string, but if this attribute is set to true the request scope bean will be retrieved from the Globals.MESSAGE_KEY constant string. Also if this is set to true, any value assigned to the name attribute will be ignored.

如果指定属性 messagetrue,则 <html:messages> tag 用于显示消息。

现在您已经使用 property 属性过滤给定 属性 的邮件。

Name of the property for which messages should be displayed. If not specified, all messages (regardless of property) are displayed.

如果您只有一条带有 field1 属性 的消息,则只会显示一条消息。

看这里如何使用操作消息对象

ActionMessages messages = new ActionMessages();
messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.common.field1.required");
saveMessages(request, messages); // storing messages as request attributes

属性文件:

error.common.field1.required = Field1 is required.

并显示消息

<logic:messagesPresent message="true">
   <html:messages id="message" message="true">
     <bean:write name="message"/><br/>
   </html:messages>
</logic:messagesPresent>

它将在全局消息键下循环所有消息。如果你想使用自定义密钥,你可以将它与 ActionMessage

的参数一起使用
messages.add("field1", new ActionMessage("error.common.field1.required");

检索消息

<logic:messagesPresent message="true">
   <html:messages id="message" property="field1" message="true">
     <bean:write name="message"/><br/>
   </html:messages>
</logic:messagesPresent>

我最终弄清楚了我的问题,它与我创建新 ActionMessage 的方式有关。

当您使用时:

public ActionMessage(<error message>, false)

虽然它允许您通过将 <html:messages> 标记与 <bean:write><c:out> 结合使用来显示文字值,但它不会为一个给出 属性,为什么我不知道。

我测试发现,如果我使用资源包并使用标准创建 ActionMessage:

public ActionMessage(<key in resource bundle>)

我可以为单个 属性.

显示多条消息

不幸的是,因为我正在使用 hibernate 验证器,所以我不想使用资源包和 struts 来替换值(宁愿让 hibernate 验证器注释替换值)并且可能只显示一个目前一次一条消息。