Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring rest internationalization

Is there a way to implement Spring internationalization into rest service if I want to setLocale on the parameter i parse from a specific user ticket?

Workflow looks like this: user clicks a link. Service gets user specific ticket and settings. Service parses ticket and gets locale this locale should be set accordingly and then service returns response in a specific language.

All I have found were samples simply transfering locale together with the request. Also I am not getting the point how Spring maps all these names. Do I have to give him the variables and then he maps those names with the language sources given?

like image 999
DasBoot Avatar asked Feb 17 '26 17:02

DasBoot


1 Answers

You have to create your application localization properties files and put them into the class path, so for e.g. you have two files:

application_en.properties
application_lt.properties

one is for english language and the other is for lithuanian. Lets say they contain one property:

en:
application.name=Example

lt:
application.name=Pavyzdys

Then you have to define a message source in your spring configuration file:

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename" value="application"/>
</bean>

Please note that basename is application and what is beyond underscore: in our case en and lt is the locale you need to give to message source to get the localized property.

For e.g.:

Lets say you have spring's message source successfully autowired in some bean:

@Autowired
private MessageSource messageSource;

and you have a method:

public String getMessage(String code, String locale) {
    return messageSource.getMessage(code, null, new Locale(locale));
}

So when you call:

getMessage("application.name", "en") - it will return you "Example" for english language.

getMessage("application.name", "lt") - it will return you "Pavyzdys" for lithuanian language.

Hope this makes sense.

like image 74
Paulius Matulionis Avatar answered Feb 20 '26 06:02

Paulius Matulionis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!