简体   繁体   中英

How to get locale in Spring WebFlux?

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);
    }
}

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:

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();

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