简体   繁体   中英

Tomcat internationalization maintenance

I am trying to implement internationalization in Tomcat. There are going to be different resource text files. My idea is to load all the resources in to the memory while tomcat loads. Below is the sample code to load multiple resource in to the memory.

public class ResourceBundleLoader {


    private static ResourceBundle enResourceBundle;
    private static ResourceBundle frResourceBundle;

    public static void loadBundle(){
        Locale enLocale = new Locale("en", "US");
        enResourceBundle = ResourceBundle.getBundle("MessagesBundle",enLocale);
        enLocale = new Locale("fr", "FR");
        frResourceBundle = ResourceBundle.getBundle("MessagesBundle",enLocale);
    }

    public static ResourceBundle getEnResourceBundle(){
        return enResourceBundle;
    }

    public static ResourceBundle getFrResourceBundle(){
        return frResourceBundle;
    }
}

The method loadBundle is called once thru startup servlet. And getEnResourceBundle() and getFrResourceBundle() is called accordingly. Is this right way to implement/maintain internationalization in tomcat? or is there any better way?

Thanks in advance.

You dont need to make this helper class, as per the java documentation the bundles are already cached for you in memory. This will just make your code more complicated to maintain. ie You would have to alter your code every time you add a new "bundle".

Just add code like this to your servlets and/or JSP's:

//request.getLocale() returns the web browsers locale
bundle = ResourceBundle.getBundle("MessagesBundle",request.getLocale())

Just make sure you have a default message bundle file with all your text. Then you can just add extra locales at will as things get translated.

UTF-8 support

I also strongly suggest you create a servlet filter that applies to all requests that ensures that UTF-8 is turned on for both the html that is output, and the parsing of the form responses that are posted back to your application:

request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");

I wouldn't optimize until I knew the i18n was too slow.

But if I proceeded down your path, instead of using scalar ResourceBundles, I'd put the ResouceBundles into a Map. Now your code can use any bundle knowing the locale - which you have to select the appropriate ResourceBundle anyway.

Your code won't have any if locale is this, use English . Instead, it will be myResourceBundle = bundleMap.get(myLocale);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM