I have the following code for some user input validation
<h:form>
<h:inputText value="#{user.input}">
<f:validator validatorId="validator.InputValidator" />
</h:inputText>
<h:commandButton action="someaction" value="submit">
</h:commandButton>
<h:messages layout="table"></h:messages>
</h:form>
It works fine, but I need to show some UTF-8 message if user input is not valid,
how can I do this?
I assume that your current problem is that characters outside the ISO-8859-1 range are been shown as mojibake. Is this true? I couldn't think of another reason for asking this trivial question. Yes? Then read ahead:
First, if you're still using old JSP instead of its successor Facelets, then you need to set the page encoding to UTF-8. Put this in top of every JSP:
<%@page pageEncoding="UTF-8" %>
or configure it globally in web.xml
:
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<page-encoding>UTF-8</page-encoding>
</jsp-property-group>
</jsp-config>
If you're using Facelets, you don't need to do anything. It uses by default already UTF-8 as response encoding.
Second, if you're obtaining the messages from .properties
files, then you need to understand that those files are by default been read using ISO-8859-1. See also java.util.Properties
javadoc:
.. the input/output stream is encoded in ISO 8859-1 character encoding. Characters that cannot be directly represented in this encoding can be written using Unicode escapes ; only a single 'u' character is allowed in an escape sequence. The
native2ascii
tool can be used to convert property files to and from other character encodings.
So, you need to write down the the characters outside the ISO-8859-1 range by Unicode escape sequences. E.g. instead of
some.dutch.text = Één van de wijken van Curaçao heet Saliña.
you need to write
some.dutch.text = \u00c9\u00e9n van de wijken van Cura\u00e7ao heet Sali\u00f1a.
This can be automated by using native2ascii
tool.
As a completely different alternative, you can supply JSF a custom ResourceBundle
implementation with a custom Control
which reads the files using UTF-8. This is in more detail expanded in this answer and this blog. This works only whenever you're providing validation messages by your own as for example requiredMessage
instead of overriding JSF default validation messages. Other than that (i.e. you need it for <message-bundle>
files), then you really need to use the native2ascii
tool.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With