问题
I would like to create a custom message renderer to renders h:message as a 'p' html element instead of as a 'span' element. It concerns the following message tag:
<h:message id="firstNameErrorMsg" for="firstname" class="error-msg" />
I've written to code underneath, but that's only rendering an empty 'p' element. I suppose I have to copy all attributes and text from the original component and write it to the writer. However, I don't know where to find everything and it seems to be a lot of work for just a replacement of a tag.
Is there a better way to get an h:message tag rendered as a 'p' element?
Code:
@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");
}
}
回答1:
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:
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; }
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" />
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>
来源:https://stackoverflow.com/questions/19730562/render-jsf-hmessage-with-p-element-instead-of-span