I have an enum where values are presented in utf8 format. Because of this i have some encoding problems in my jsp view. Is there a way to get values from my messages.properties
file. What if i have following lines in my properties file:
shop.first=Первый
shop.second=Второй
shop.third=Третий
How can i inject them in enum?
public enum ShopType {
FIRST("Первый"), SECOND("Второй"), THIRD("Третий");
private String label;
ShopType(String label) {
this.label = label;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
}
I often have similar use cases, which I handle by putting the keys (not the localized values) as enum properties. Using a ResourceBundle
(or a MessageSource
when using Spring), I can resolve any such localized string whenever needed. This approach has two advantages:
.properties
file, which eliminates all encoding concerns in Java classes;.properties
file per locale).This way, your enum will look like:
public enum ShopType {
FIRST("shop.first"), SECOND("shop.second"), THIRD("shop.third");
private final String key;
private ShopType(String key) {
this.key = key;
}
public String getKey() {
return key;
}
}
(I removed the setter since an enum property should always be read-only. Anyway, it's not necessary anymore.)
Your .properties
file remains the same.
Now comes the time to get a localized shop name...
ResourceBundle rb = ResourceBundle.getBundle("shops");
String first = rb.getString(ShopType.FIRST.getKey()); // Первый
Hope this will help...
Jeff
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With