简体   繁体   中英

Spring boot Rest API internationlization based on request parameter

We have a spring boot REST application with APIs having both GET and POST methods.We have few response messages that need to internationalized based on a parameter "locale" for both GET and POST.In case of GET,locale will be passed as query parameter(eg: http://sampleapp/search?locale=en ) and for POST method,locale will be part of request JSON. It would be great if I could get some reference implementation for this scenario.

At first I think you do not need to have locale path param. Instead of you can use the standard Accept-Language HTTP header property. You can read about this header here .

This is the way how you can read the accept-language information from the HTTP request in your rest method:

@RequestMapping(produces = "application/json", method = RequestMethod.GET)
public ResponseEntity<Data> getData(@RequestHeader(value="Accept-Language") String acceptLanguage)
{
    //your code goes here
}

Once you get the accepted language info from your client' then you can read language deppendent values from a property file with Java I18N. The following article explain you the way how to do it: https://www.google.hu/amp/s/www.journaldev.com/1370/java-i18n-internationalization-in-java/amp

Finnaly if the language info is not provided by client you can use english language as a default.

Hope that it will help you.

The standard way of detecting user locale in web applications which can be reused in REST services is accept-language header. Browsers send this header with every request automatically. When it comes to detecting user locale in Spring MVC applications Spring provides us with a variety of *LocaleResolver classes that do the job for us. Please refer this article for simple example.

Provided that you are using Spring REST extension to Spring MVC then it is no different here. Everything that is available for MVC can be used in @RestController ones. So you clients may set the accept-language on their requests and automatic detection will work the same way as in web application.

If you have a requirement implement a solution with locale as a POST/GET parameter then you should have a look at LocaleContextHolder . Spring associates a locale information with the current Thread and this is a way to directly access and modify it. When you set the locale using LocaleContextHolder later you can use it in your app components reading form the context as well as Spring standard components will be aware of another locale set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM