This recipe demonstrates how to create a stateless service in Lagom for Java that uses Play's Internationalization Support.
The hello-i18n-impl/src/main/resources
directory contains configuration:
application.conf
defines theplay.i18n.langs
property with supported locale codesmessages
contains the default message keysmessages.de-DE
andmessages.es-ES
show how to specify messages for alternate locales
The implementation is in HelloServiceImpl
:
- A
MessagesApi
instance is injected into the constructor. - The
helloWithLang
service call usesMessagesApi.preferred(Collection<Lang>)
with a singleton collection containing the specifiedLang
. This uses Play's fallback logic to select the closest matchingMessages
instance. - The
hello
service call uses service call composition andPlayServiceCall
to wrap a service call with a PlayEssentialAction
so that it can obtain the PlayRequestHeader
object and pass that toMessagesApi.preferred(Http.RequestHeader)
. - Both version call through to a private helper method that looks up the message string, passing the
id
service call parameter as an argument to theMessageFormat
.
You can test this recipe using 2 separate terminals.
On one terminal start the service:
mvn lagom:runAll
On a separate terminal, use curl
to request messages in various languages. There are two ways to do it, by passing a locale parameter in the URL, or by specifying the 'Accept-Language' header.
First, with the URL parameter:
$ curl http://localhost:9000/api/hello/en/Alice && echo
Hello, Alice!
$ curl http://localhost:9000/api/hello/es/Alice && echo
¡Hola, Alice!
$ curl http://localhost:9000/api/hello/de-DE/Alice && echo
Hallo, Alice!
$ curl http://localhost:9000/api/hello/fr-FR/Alice && echo # missing, falls back to en
Hello, Alice!
Alternatively with the 'Accept-Language' header:
$ curl http://localhost:9000/api/hello/Alice && echo # default, uses en
Hello, Alice!
$ curl -H 'Accept-Language: es-ES' http://localhost:9000/api/hello/Alice && echo # with a full locale code
¡Hola, Alice!
$ curl -H 'Accept-Language: es' http://localhost:9000/api/hello/Alice && echo # just the language code
¡Hola, Alice!
$ curl -H 'Accept-Language: de-CH' http://localhost:9000/api/hello/Alice && echo # missing, falls back to en
Hello, Alice!
$ curl -H 'Accept-Language: de-CH, de' http://localhost:9000/api/hello/Alice && echo # or you can specify a list to use the first match
Hallo, Alice!