A question which keeps coming back is how to show HTML in <h:messages>, for example a link in a message. The obvious attempt is an escape="false" attribute, like on <h:outputText>. Jakarta Faces (formerly known as JSF), however, has no such attribute on <h:messages> and <h:message>, not even in Faces 5.0. This article explains why, shows the safe way to do it anyway with a small custom renderer, and ends with the ready-to-use <o:messages> of OmniFaces. It targets Faces 4.0 and newer. The differences for JSF 2.x and JSF 1.2 are at the bottom.
The problem
Here's a form with a numeric field, and an action method which adds a message with a link.
<h:form id="form">
<h:inputText id="quantity" value="#{bean.quantity}" label="Quantity" />
<h:message for="quantity" />
<h:commandButton id="submit" value="Submit" action="#{bean.submit}" />
<h:messages id="messages" globalOnly="true" />
</h:form>
@Named
@RequestScoped
public class Bean {
private Long quantity;
public void submit() {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Please accept the <a href=\"terms.xhtml\">terms</a> first."));
}
// +getter+setter
}
Submit the form, and the message shows up literally, with the tags as text. The HTML source tells why:
<ul id="form:messages"><li>Please accept the <a href="terms.xhtml">terms</a> first.</li></ul>
The message renderer writes the summary with ResponseWriter#writeText(), which escapes HTML. That's on purpose.
Why there is no escape attribute
Messages don't only come from your own code. Faces creates messages itself, and those often contain what the user has typed. Enter <b>bold</b> in the quantity field and submit. The LongConverter fails with this message:
Quantity: '<b>bold</b>' must be a number consisting of one or more digits.
Rendered unescaped, the word "bold" really ends up bold in the page. And what works with <b> works with <script> too. That's an XSS hole. The same applies to messages built from data out of the database, or from any other source you don't control. So unescape only messages whose whole text comes from you.
Fortunately, Faces itself helps here. A message from a converter or validator is always attached to the client ID of its input component. A message which you add with a null client ID is a global message. The globalOnly="true" attribute of <h:messages> shows only the global messages. So the plan is: show your own HTML messages unescaped in a separate <h:messages globalOnly="true">, and leave all other messages escaped.
Iterating the messages yourself
Without any extra code, you can iterate over the messages in the view and print each one with <h:outputText escape="false">.
<ui:repeat value="#{facesContext.messageList}" var="message">
<div><h:outputText value="#{message.summary}" escape="false" /></div>
</ui:repeat>
This shows the link. But getMessageList() returns all messages, including the converter message with the <b>bold</b> of the user. On Mojarra that one is now also rendered unescaped. On MyFaces it doesn't show up at all, and neither would any other message: while there are error messages, the <ui:repeat> of MyFaces keeps the list it got before the messages were added, which is an empty one. There's an overload which takes a client ID, but #{facesContext.getMessageList(null)} doesn't give the global messages: EL coerces the null to an empty string for a String argument, and there are no messages for client ID "".
What does work is a stream which filters out the messages of the inputs.
<ui:repeat value="#{facesContext.messageList.stream().filter(message -> not facesContext.getMessageList('form:quantity').contains(message)).toList()}" var="message">
<div><h:outputText value="#{message.summary}" escape="false" /></div>
</ui:repeat>
Now the link shows up, and the converter message with the <b>bold</b> doesn't. But a FacesMessage doesn't know its client ID, so the filter can only leave out the client IDs you list yourself. That has to be every input in the form. Add an input later and forget the filter, and its messages are rendered unescaped again. Filtering on "all inputs" in EL isn't possible either: #{facesContext.clientIdsWithMessages} is an Iterator, and EL can't stream that. You'd also lose everything else <h:messages> offers, such as for, layout, showDetail and the style classes per severity. What you really want is <h:messages globalOnly="true" escape="false">.
A custom renderer
Facelets accepts an unknown attribute such as escape on <h:messages>; it simply ends up in the attributes of the component. All you need is a renderer which does something with it. Copying the message renderer of the Faces implementation in order to change the call to writeText() ties your code to the internals of Mojarra or MyFaces. Wrap it instead. The renderer below wraps the standard renderer, and wraps the ResponseWriter during the rendering when escape="false" is set. The writer then writes the text as is.
package com.example;
import java.io.IOException;
import jakarta.faces.component.UIComponent;
import jakarta.faces.context.FacesContext;
import jakarta.faces.context.ResponseWriter;
import jakarta.faces.context.ResponseWriterWrapper;
import jakarta.faces.render.Renderer;
import jakarta.faces.render.RendererWrapper;
public class EscapableMessagesRenderer extends RendererWrapper {
public EscapableMessagesRenderer(Renderer<?> wrapped) {
super(wrapped);
}
@Override
public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
if (!"false".equals(String.valueOf(component.getAttributes().get("escape")))) {
super.encodeEnd(context, component);
return;
}
var writer = context.getResponseWriter();
context.setResponseWriter(new UnescapedTextResponseWriter(writer));
try {
super.encodeEnd(context, component);
}
finally {
context.setResponseWriter(writer);
}
}
private static class UnescapedTextResponseWriter extends ResponseWriterWrapper {
UnescapedTextResponseWriter(ResponseWriter wrapped) {
super(wrapped);
}
@Override
public void writeText(Object text, UIComponent component, String property) throws IOException {
write(String.valueOf(text));
}
@Override
public void writeText(Object text, String property) throws IOException {
write(String.valueOf(text));
}
}
}
The renderer must replace the standard renderers of <h:messages> and <h:message>. The standard way to wrap a standard renderer is a RenderKitWrapper, installed via a RenderKitFactory. That's the same pattern as in Styling options in select components in JSF and Faces.
package com.example;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import jakarta.faces.render.RenderKit;
import jakarta.faces.render.RenderKitWrapper;
import jakarta.faces.render.Renderer;
public class EscapableMessagesRenderKit extends RenderKitWrapper {
private static final Set<String> FAMILIES = Set.of("jakarta.faces.Messages", "jakarta.faces.Message");
private final Map<Renderer<?>, Renderer<?>> renderers = new ConcurrentHashMap<>();
public EscapableMessagesRenderKit(RenderKit wrapped) {
super(wrapped);
}
@Override
public Renderer<?> getRenderer(String family, String rendererType) {
var renderer = getWrapped().getRenderer(family, rendererType);
return renderer != null && FAMILIES.contains(family) ? renderers.computeIfAbsent(renderer, EscapableMessagesRenderer::new) : renderer;
}
}
package com.example;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import jakarta.faces.context.FacesContext;
import jakarta.faces.render.RenderKit;
import jakarta.faces.render.RenderKitFactory;
public class EscapableMessagesRenderKitFactory extends RenderKitFactory {
private final Map<RenderKit, RenderKit> renderKits = new ConcurrentHashMap<>();
public EscapableMessagesRenderKitFactory(RenderKitFactory wrapped) {
super(wrapped);
}
@Override
public RenderKit getRenderKit(FacesContext context, String renderKitId) {
var renderKit = getWrapped().getRenderKit(context, renderKitId);
return HTML_BASIC_RENDER_KIT.equals(renderKitId) && renderKit != null ? renderKits.computeIfAbsent(renderKit, EscapableMessagesRenderKit::new) : renderKit;
}
@Override
public void addRenderKit(String renderKitId, RenderKit renderKit) {
getWrapped().addRenderKit(renderKitId, renderKit);
}
@Override
public Iterator<String> getRenderKitIds() {
return getWrapped().getRenderKitIds();
}
}
Register the factory in faces-config.xml.
<factory>
<render-kit-factory>com.example.EscapableMessagesRenderKitFactory</render-kit-factory>
</factory>
Now this works:
<h:messages id="messages" globalOnly="true" escape="false" />
The link in your own message is a real link now. Enter <b>bold</b> again, and the converter message doesn't show up in there at all, because it isn't global. It still shows up escaped in the <h:message for="quantity">. The escape="false" works on <h:message> too, but there it's nearly always a bad idea, because the messages for an input come from its converter and validators. This was tested on Mojarra 4.1.21 (WildFly 42) and MyFaces 4.1.4 (Tomcat 11), with exactly the same output.
OmniFaces messages
With OmniFaces, all of the above is one tag. The <o:messages> extends <h:messages> with an escape attribute, among other things.
<o:messages id="messages" globalOnly="true" escape="false" />
It renders exactly the same as the custom renderer above, also when it comes to the converter message. Again, combine escape="false" with globalOnly="true", or with a for which points to a component that only gets your own messages. The <o:messages> can also take full control over the markup with a var. That's handy when a message needs more than a bit of HTML in its text.
<o:messages globalOnly="true" var="message">
<div class="alert"><h:outputText value="#{message.summary}" escape="false" /></div>
</o:messages>
PrimeFaces users have an escape attribute on <p:messages> as well. The same advice applies to it.
JSF 2.x
On JSF 2.x the same works with javax.* packages instead of jakarta.*, and with javax.faces.Messages and javax.faces.Message as family names. The constructors of the wrapper classes which take the wrapped instance exist only since JSF 2.3. On JSF 2.0 to 2.2, keep the wrapped instance in a field and override getWrapped() to return it. The RendererWrapper exists only since JSF 2.2; on JSF 2.0 and 2.1 extend Renderer and delegate every method to the wrapped renderer yourself. The <o:messages escape> is available since OmniFaces 1.5.
JSF 1.2
On JSF 1.2 there was no RenderKitWrapper yet, so the usual approach was to extend the messages renderer of the JSF implementation, replace the ResponseWriter in its encodeEnd() as above, and register it in the <render-kit> of faces-config.xml. That depended on the internals of the implementation. If you're still on JSF 1.2, upgrade.

19 comments:
Indeed. I also stumbled upon this question. Thx for this solution!
Hello!
Can i translate some of your posts into Russian language? Sure with all needed copyrights. Please email me about this:
ahriman@tpu.ru
Doing this is probably unwise because of HTML/code injection issues - unless you exercise a strong degree of control over your application and its dependencies (including all 3rd party libraries and the JEE platform implementation). You don't know what data will be added to the message queue.
If you replaced the h:message (no S) renderer instead, you'd be on safer ground because each component targets something you've specified in the view.
I'm not saying "don't do this", but I think the post is incomplete without a follow-up describing all the bad things you could do with it.
Right, as long as you don't redisplay user-controlled input in messages, this is fine.
good article tnx...
I tried this, too, but the JSP compiler then fails saying that the "escape" attribute is not valid for the h:messages tag. I suppose I need to hack the TLD, too? That seems a bit kludgy.
thanks for saving me a lot of time with this neat solution.
what problems can cuase this i read mcdowells post and i got confused if its a good solution to apply or not, BalusC, can you please explain what might cause in my app if i use this class, cause i tried it for H:message, as u said i replaced it and it works perfectly but i want to know waht can happen..what messages can not be redisplayed???... thx
can i do the same for the rich:message? which package is it??
Just what I needed... Thanks man!
This is not working for me! I have added the class, and changed faces-config.xml to look as follows:
<?xml version="1.0" encoding="UTF-8"?>
<faces-config
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
version="2.0">
<render-kit>
<renderer>
<component-family>javax.faces.Messages</component-family>
<renderer-type>javax.faces.Messages</renderer-type>
<renderer-class>microworks.voyagernetz.bazaar.EscapableMessagesRenderer</renderer-class>
</renderer>
</render-kit>
</faces-config>
The contents of the <h:messages escape="false"> tag is still escaped.
I use Glassfish 3.1.2. Any ideas?
Myfaces 2.1, HtmlMessageRendererBase, calls writer.writeText(detail, null);
so you need to override writeText(text, property)
not writeText(text, component, property)
Regards,
Neil
@Neil: indeed, that depends on the JSF implementation you're currently using. The article also explicitly mentions "the standard JSF implementation", referring to Mojarra (com.sun.faces.*).
Could somebody tell me how to import com.sun.faces.renderkit.html_basic.MessagesRenderer? I use Websphere Application Server.
Hi, I know this is an old article, but I am still using JSF 1.2 (can't upgrade to 2.0 just yet). I followed the instructions to the letter, also removing the annotation, and I get the following server error :
Unable to locate tag attribute info for tag attribute escape.
Is there something else I need to set up?
Thanks in advance
Excellent Job. What if I want the message text, icon to appear from right to left. What changes are needed on the code? Thanks a lot.
Thank you, you save my day on this legacy issue with JSF, Why people still using JSF
Thanks, I worked without problems with the following JAR:
jsf-api-1.2_12.jar
jsf_facelets-1.1.15.B1.jar
jsf_impl-1.2_12.jar
My faces-config:
com.sun.facelets.FaceletViewHandler
es
es
cl.gov.subdere.seam.CustomPhaseListener
javax.faces.Messages
javax.faces.Messages
cl.gov.subdere.util.EscapableMessagesRenderer
My File Path the class in EJB:
project\trunk\ejb\src\main\java\cl\gov\subdere\util\EscapableMessagesRenderer.java
My hero!!! Worked like a charm!!!! Thanks a lot!
Post a Comment