加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 如何将JSF消息编码设置为UTF-8?

发布时间:2020-12-14 23:59:25 所属栏目:Java 来源:网络整理
导读:我有一些用户输入验证的代码 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>
    <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>

它工作正常,但如果用户输入无效,我需要显示一些UTF-8消息,
我怎样才能做到这一点?

解决方法

我假设您当前的问题是ISO-8859-1范围之外的字符显示为 mojibake.这是真的吗?我想不出提出这个微不足道的问题的另一个原因.是?然后预读:

首先,如果您仍在使用旧JSP而不是其后继Facelets,那么您需要将页面编码设置为UTF-8.把它放在每个JSP的顶部:

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

或者在web.xml中全局配置它:

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

如果您使用的是Facelets,则无需执行任何操作.它默认使用UTF-8作为响应编码.

其次,如果您从.properties文件中获取消息,则需要了解默认情况下这些文件是使用ISO-8859-1读取的.另见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.

因此,您需要在Unicode escape sequences之前记下ISO-8859-1范围之外的字符.代替

some.dutch.text = één van de wijken van Cura?ao heet Sali?a.

你需要写

some.dutch.text = u00c9u00e9n van de wijken van Curau00e7ao heet Saliu00f1a.

这可以通过使用native2ascii工具自动完成.

作为一个完全不同的替代方案,您可以使用自定义Control为JSF提供自定义ResourceBundle实现,该自定义Control使用UTF-8读取文件.这在this answer和this blog中进行了更详细的扩展.只有在您自己提供验证消息时才会起作用,例如requiredMessage,而不是覆盖JSF默认验证消息.除此之外(即你需要< message-bundle>文件),那么你真的需要使用native2ascii工具.

也可以看看:

> Unicode – How to get the characters right?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读