Reputation: 1569
I want to get current locale but the context always return default locale. It works with MVC but not with WebFlux.
Thank for your help!
package co.example.demo.controller;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Locale;
@RestController
@RequestMapping("/hello")
public class HelloController {
private final MessageSource messageSource;
public HelloController(MessageSource messageSource) {
this.messageSource = messageSource;
}
@GetMapping
public String hello() {
Locale locale = LocaleContextHolder.getLocale();
return messageSource.getMessage("hello", null, locale);
}
}
Upvotes: 4
Views: 3640
Reputation: 21
Earlier I was using spring-web dependency in my project and was able to get locale from WebRequest.
But when we have migrated project from spring-web to spring-web-flux then we can get locale using LocaleContextHolder as below:
Locale locale = LocaleContextHolder.getLocale();
Upvotes: 1
Reputation: 8297
Do not use LocaleContextHolder
in WebFlux environment but add Locale
as a method parameter instead:
@RestController
public class LocaleController {
@GetMapping("/locale")
String getLocale(Locale locale) {
return locale.toLanguageTag();
}
}
Test:
$ curl localhost:8080/locale -H 'Accept-Language: en-US'
en-US
$ curl localhost:8080/locale -H 'Accept-Language: en-GB'
en-GB
For more info see:
Upvotes: 8