如何使用Velocity模板正确显示西班牙语字符?

时间:2015-06-17 16:59:27

标签: java velocity

我正在使用Velocity和消息资源包来生成html页面。当我将墨西哥指定为我的语言环境时,我的messages-es_MX.properties将被处理为消息资源的源。这正如我所料。但是人物(áéíóúüñ¿)没有正确显示。

我的讯息属性:

customer.greeting=áéíóúüñ¿¡

对于我的第一次尝试,我有以下内容:

  • 生成页面中的html标题:<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  • 速度属性包含:
    • input.encoding = utf-8
    • output.encoding = UTF-8
  • html文件编码:UTF-8
  • messages_es_MX.properties encoding:ISO-8859-1

输出到${customer.greeting}的html:

�������

然后我意识到属性文件的编码不正确;它也应该是UTF-8。

第二次尝试:

  • 生成页面中的html标头:<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    • 速度属性包含:
      • input.encoding = utf-8
      • output.encoding = UTF-8
  • html文件编码:UTF-8
  • messages_es_MX.properties encoding:UTF-8

输出到html:

áéíóúüñ¿¡

有关如何使其发挥作用的任何建议吗?

1 个答案:

答案 0 :(得分:0)

嗯,事实证明这比我想象的要复杂,但这是解决方案。在开始之前,请确保所有html和属性文件都以UTF-8编码。并且所有Velocity配置也参考UTF-8。不应该引用ISO-8859-1。

根本问题是,默认情况下,ResourceBundle假定属性文件采用ISO-8859-1编码。可以覆盖它,但需要一段自定义代码。

而不是打电话

ResourceBundle bundle = ResourceBundle.getBundle("messages", MEXICO);

我需要为自定义Control实现添加一个参数:

ResourceBundle bundle = ResourceBundle.getBundle("messages", MEXICO, new UTF8Control());

UTF8Control类如下所示:

package test;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Locale;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import java.util.ResourceBundle.Control;

public class UTF8Control extends Control {

    public ResourceBundle newBundle(String baseName, Locale locale,
            String format, ClassLoader loader, boolean reload)
            throws IllegalAccessException, InstantiationException, IOException {

        // The below is a copy of the default implementation.
        String bundleName = toBundleName(baseName, locale);
        String resourceName = toResourceName(bundleName, "properties");
        ResourceBundle bundle = null;
        InputStream stream = null;
        if (reload) {
            URL url = loader.getResource(resourceName);
            if (url != null) {
                URLConnection connection = url.openConnection();
                if (connection != null) {
                    connection.setUseCaches(false);
                    stream = connection.getInputStream();
                }
            }
        } else {
            stream = loader.getResourceAsStream(resourceName);
        }
        if (stream != null) {
            try {
                // Only this line is changed to make it to read properties files
                // as UTF-8.
                bundle = new PropertyResourceBundle(new InputStreamReader(
                        stream, "UTF-8"));
            } finally {
                stream.close();
            }
        }
        return bundle;
    }

}

归功于最初发布this related answer的@BalusC。

所以,第1部分解决了。但是仍然存在问题,因为我使用的是VelocityTools,我可以在ResourceTool的源代码中看到它调用ResourceBundle.getBundle(...)而不传递任何Control实现。这意味着它将使用ISO-8859-1,我无法传入我的UTF8Control ......

除非我覆盖ResourceTool类的方法来获取包:

package test;

import java.util.Locale;
import java.util.ResourceBundle;

import org.apache.velocity.tools.ConversionUtils;
import org.apache.velocity.tools.generic.ResourceTool;

public class UTF8ResourceTool extends ResourceTool {

    /**
     * Retrieves the {@link ResourceBundle} for the specified baseName and
     * locale, if such exists, using UTF-8 encoding. If the baseName or locale is null or if the
     * locale argument cannot be converted to a {@link Locale}, then this will
     * return null.
     */
    protected ResourceBundle getBundle(String baseName, Object loc) {
        Locale locale = (loc == null) ? getLocale() : toLocale(loc);
        if (baseName == null || locale == null) {
            return null;
        }
        return ResourceBundle.getBundle(baseName, locale, new UTF8Control());
    }

    /* Copied here from parent class because it's private there */
    private Locale toLocale(Object obj) {
        if (obj == null) {
            return null;
        }
        if (obj instanceof Locale) {
            return (Locale) obj;
        }
        String s = String.valueOf(obj);
        return ConversionUtils.toLocale(s);
    }

}

在我的UTF8ResourceTool类中,我只覆盖一个方法getBundle(我必须从父类逐字复制一个私有方法)。获取资源包时,重写的方法将UTFControl作为第三个参数传递,以便我们可以使用UTF-8编码提取资源。

现在唯一要做的就是更新我的Velocity配置,以便我引用自定义UTF8ResourceTool而不是Velocity Tools&#39; ResourceTool

        EasyFactoryConfiguration config = new EasyFactoryConfiguration();
    config.toolbox(Scope.APPLICATION).tool("msg", UTF8ResourceTool.class)
            .property("bundles", "messages/messages").property("locale", locale)
            .tool("date", DateTool.class).tool("number", NumberTool.class)
            .tool("string", StringTool.class).tool("esc", EscapeTool.class)
            .tool("base64", Base64Tool.class);

将所有内容放在一起,${customer.greeting}的html输出为:

áéíóúüñ¿¡