Java – how to set JSF message encoding to UTF-8?

I have some user input validation code

<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 normally, but if the user input is invalid, I need to display some UTF-8 messages. How can I do this?

Solution

I assume that your current problem is that characters outside the scope of iso-8859-1 are displayed as mojibake But is it really the case? I can't think of another reason for raising this trivial question Yes? Then read ahead:

First, if you are still using the old JSP instead of its successor facelets, you need to set the page encoding to UTF - 8 Put it at the top of each jsp:

<%@page pageEncoding="UTF-8" %>

Or on the web Configure it globally in XML:

<jsp-config>
    <jsp-property-group>
        <url-pattern>*.jsp</url-pattern>
        <page-encoding>UTF-8</page-encoding>
    </jsp-property-group>
</jsp-config>

If you are using facelets, no action is required It uses UTF - 8 as the response encoding by default

Second, if you start from To get messages from the properties file, you need to understand that these files are read using iso-8859-1 by default See also Java util. Properties javadoc:

Therefore, you need to write down characters outside the iso-8859-1 range before Unicode escape sequences replace

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 done automatically by using the native2a SCII tool

As a completely different alternative, you can use a custom control to provide a custom resourcebundle implementation for JSF, which uses UTF-8 to read files This is extended in more detail in this answer and this blog It works only when you provide the validation message yourself, such as requiredmessage, instead of overriding the JSF default validation message In addition (that is, you need the < message bundle > file), you really need to use the native2ascii tool

You can also see:

> Unicode – How to get the characters right?

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>