2013-11-27 49 views
2

我在添加多语言到我的网站时遇到了一些麻烦。为什么ResourceBundle.getBundle(String,Locale)忽略Locale?

它对jstl的.jsp文件工作正常,但是当我尝试使用Java代码获取翻译时,它会忽略Locale参数并使用客户端浏览器区域设置。

我:

两个属性文件: dictionary.properties,包含:validate.firstname.empty=You have to enter a first name dictionary_nl.properties,包含:validate.firstname.empty=U heeft geen voornaam ingevuld

而这个Java代码:

public List<String> validate(UserForm user, Locale locale) 
{ 
    List<String> errors = new ArrayList<>(); 
    ResourceBundle resources = ResourceBundle.getBundle("dictionary", new Locale("en")); 

    if (user.getFirstName() == null || user.getFirstName().trim().isEmpty()) 
    { 
     errors.add(resources.getString("validate.firstname.empty")); 
    } 
    return errors; 
} 

出于测试目的,我插入了一个Locale的新实例到getBundle,但是如果我的浏览器设置为荷兰语,它仍会返回荷兰语翻译,如果浏览器设置为英文,则为英文翻译。

回答

3

事实上的getBundle()不忽略语言环境,它只是似乎忽略它在你的配置

由于配置中没有dictionary_en.properties文件,语言“en”的区域设置在ResourceBundle文件搜索中将不起作用。

而是使用new Locale("nl")进行测试,无论在浏览器中设置何种语言,您都将获得荷兰语翻译。

文档中的更多细节:
http://docs.oracle.com/javase/6/docs/api/java/util/ResourceBundle.html#getBundle%28java.lang.String,%20java.util.Locale,%20java.lang.ClassLoader%29

相关问题