4

我想创建一个自定义消息渲染器来将 h:message 渲染为“p”html 元素而不是“span”元素。它涉及以下消息标签:

<h:message id="firstNameErrorMsg" for="firstname" class="error-msg"  />

我已经编写了下面的代码,但这只是呈现一个空的“p”元素。我想我必须从原始组件中复制所有属性和文本并将其写入编写器。但是,我不知道在哪里可以找到所有东西,而且仅仅更换标签似乎需要做很多工作。

有没有更好的方法将 h:message 标记呈现为“p”元素?

代码:

@FacesRenderer(componentFamily = "javax.faces.Message", rendererType = "javax.faces.Message")
public class FoutmeldingRenderer extends Renderer {

    @Override
    public void encodeEnd(final FacesContext context, final UIComponent component) throws IOException {

        ResponseWriter writer = context.getResponseWriter();
        writer.startElement("p", component);
        writer.endElement("p");

    }
}
4

1 回答 1

7

It isn't exactly "a lot of work". It's basically a matter of extending from the standard JSF messages renderer, copypasting its encodeEnd() method consisting about 200 lines then editing only 2 lines to replace "span" by "p". It's doable in less than a minute.

But yes, I agree that this is a plain ugly approach.

You can consider the following alternatives which are not necessarily more easy, but at least more clean:

  1. First of all, what's the semantic value of using a <p> instead of a <span> in this specific case? To be honest, I'm not seeing any semantic value for this. So, I suggest to just keep it a <span>. If the sole functional requirement is to let it appear like a <p>, then just throw in some CSS. E.g.

    .error-msg {
        display: block;
        margin: 1em 0;
    }
    

  2. You can obtain all messages for a particular client ID directly in EL as follows, assuming that the parent form has the ID formId:

    #{facesContext.getMessageList('formId:firstName')}
    

    So, to print the summary and detail of the first message, just do:

    <c:set var="message" value="#{facesContext.getMessageList('formId:firstName')[0]}" />
    <p title="#{message.detail}">#{message.summary}</p>
    

    You can always hide it away into a custom tag file like so:

    <my:message id="firstNameErrorMsg" for="firstname" class="error-msg" />
    

  3. Use OmniFaces <o:messages>. When the var attribute is specified, then you can use it like an <ui:repeat>.

    <o:messages for="firstNameErrorMsg" var="message">
        <p title="#{message.detail}">#{message.summary}</p>
    </o:messages>
    
于 2013-11-01T19:40:26.700 回答