Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GWT: Accessing i18n messages in server code

Tags:

java

gwt

I have an interface that extends the com.google.gwt.i18n.client.Messages class, which I use for retrieving i18n messages in my GWT application. It looks like this:

public interface MyMessages extends com.google.gwt.i18n.client.Messages {
  @DefaultMessage("Hello world")
  @Key("message1")
  String message1();

  @DefaultMessage("Hello again")
  @Key("message2")
  String message2();

  //...
}

Normally, I create an instance of it using GWT.create() like so:

private MyMessages messages = GWT.create(MyMessages.class);

However, this does not work with server-side code, only client-side code (it throws an error saying that GWT.create() is only usable in client-side code).

The answer to a similar question points to a separate library that you can download which will let you access the i18n messages on the server, but I don't want to download any extra libraries (this seems like a simple problem, there must be a simple solution).

In summary: How can I access my i18n messages in server-side code? Thanks.

like image 354
Michael Avatar asked Oct 14 '11 15:10

Michael


3 Answers

On the server side you can use the standard Java localization tools like ResourceBundle. Look here for a tutorial how to use it.

// Create a ResourceBundle out of your property files
ResourceBundle labels =
  ResourceBundle.getBundle("LabelsBundle", currentLocale);

// Get localized value
String value = labels.getString(key);

The GWT specific way of creating an interface out of your property files and providing implementations via deferred binding can not be used on sever side Java.

If you are fearless and willing to spend the time, you can implement a code generation step to read your property files and generate implementation classes for your message interface. That's exactly what the Google GWT compiler does behind the scene.

like image 138
vanje Avatar answered Nov 18 '22 16:11

vanje


I agree with Michael.. I was having this problem of trying to "localize" messages generated on the server.... but I decided to instead just throw an Exception on the server (because it is an error message which should only happen exceptionally) which contains the message code, which the client code can then look up and show the correct localized message to the user.

like image 28
Renato Avatar answered Nov 18 '22 17:11

Renato


There's a great library for GWT internationalization gwt-dmesg. It allows you to 'share' .properties files between clent and server. However, project looks to be abandoned by author and you must recompile it manually for use with GWT versio >= 2.1.0.

like image 38
beastieboy Avatar answered Nov 18 '22 18:11

beastieboy