gpt4 book ai didi

jsf - 如何编号JSF错误消息并将编号附加到无效组件

转载 作者:行者123 更新时间:2023-12-03 09:30:44 25 4
gpt4 key购买 nike

我想对用户在几个输入字段中输入无效输入时出现的所有JSF错误消息(例如验证,转换消息)进行编号。例如,当用户发送表单时,如下所示:

  • 名称不能包含数字
  • 电子邮件不正确

  • - - - 形式 - - -

    (1)姓名:约翰13母鹿

    年龄:30

    (2)电子邮件:myemail @ domain

    我怎样才能做到这一点?

    此致

    最佳答案

    对于消息部分,只需使用<h:messages/>将它们全部显示,就像您将样式设置为list-style-type: decimal;一样。那会显示数字而不是项目符号。

    下一步将为标签编号。这需要更多的工作,因为JSF没有提供任何内置的工具来解决这个问题。基本上,您需要确定所讨论的标签是否与邮件相关联,以及邮件的排队顺序。您可以按以下方式将此信息收集到Map<String, String>中:

    private Map<String, String> messageIndexes;

    public Map<String, String> getMessageIndexes() {
    FacesContext context = FacesContext.getCurrentInstance();
    if (messageIndexes == null && context.getRenderResponse()) {
    messageIndexes = new HashMap<String, String>();
    Iterator<String> clientIds = context.getClientIdsWithMessages();
    for (int i = 1; clientIds.hasNext(); i++) {
    messageIndexes.put(clientIds.next(), String.format("(%d)", i));
    }
    }
    return messageIndexes;
    }

    然后按以下方式使用它:
    <h:form id="form">
    <h:outputText value="#{bean.messageIndexes['form:input1']}" />
    <h:outputLabel for="input1">Label 1</h:outputLabel>
    <h:inputText id="input1" value="#{bean.input1}" required="true" />
    <br />
    <h:outputText value="#{bean.messageIndexes['form:input2']}" />
    <h:outputLabel for="input2">Label 2</h:outputLabel>
    <h:inputText id="input2" value="#{bean.input2}" required="true" />
    <br />
    ...
    </h:form>

    如果客户端ID在 map 中不存在,则将不会呈现任何内容。

    要将所有作业移出Bean,可以考虑使用 PhaseListener(在 beforePhase()RENDER_RESPONSE中进行操作)或自定义标签组件。

    关于jsf - 如何编号JSF错误消息并将编号附加到无效组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2503921/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com