GWT I18N on the server side

前端 未结 2 1455
醉酒成梦
醉酒成梦 2020-12-30 08:09

What is the best way to implement GWT Server Side Internationalization?

  1. Use native Java properties files (not sure how to read and how to locate the right l

2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-30 08:44

    Following other threads here in SO, I came up with this solution that also considers the encoding used for the properties files (which can be troublesome as ResourceBundle uses by default "ISO-8859-1"):

    import java.io.UnsupportedEncodingException;
    import java.util.Locale;
    import java.util.ResourceBundle;
    
    public class MyResourceBundle {
    
        // feature variables
        private ResourceBundle bundle;
        private String fileEncoding;
    
        public MyResourceBundle(Locale locale, String fileEncoding){
            this.bundle = ResourceBundle.getBundle("com.app.Bundle", locale);
            this.fileEncoding = fileEncoding;
        }
    
        public MyResourceBundle(Locale locale){
            this(locale, "UTF-8");
        }
    
        public String getString(String key){
            String value = bundle.getString(key); 
            try {
                return new String(value.getBytes("ISO-8859-1"), fileEncoding);
            } catch (UnsupportedEncodingException e) {
                return value;
            }
        }
    }
    

    The way to use this would be very similar than the regular ResourceBundle usage:

    private MyResourceBundle labels = new MyResourceBundle("es", "UTF-8");
    String label = labels.getString(key)
    

    Or you can use the alternate constructor which uses UTF-8 by default:

    private MyResourceBundle labels = new MyResourceBundle("es");
    

提交回复
热议问题