Gea*_*any 4 java locale spring-boot spring-webflux
我想获取当前语言环境,但上下文始终返回默认语言环境。它适用于 MVC,但不适用于 WebFlux。
感谢您的帮助!
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);
}
}
Run Code Online (Sandbox Code Playgroud)
不要LocaleContextHolder在 WebFlux 环境中使用,而是添加Locale为方法参数:
@RestController
public class LocaleController {
@GetMapping("/locale")
String getLocale(Locale locale) {
return locale.toLanguageTag();
}
}
Run Code Online (Sandbox Code Playgroud)
测试:
$ curl localhost:8080/locale -H 'Accept-Language: en-US'
en-US
$ curl localhost:8080/locale -H 'Accept-Language: en-GB'
en-GB
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅:
| 归档时间: |
|
| 查看次数: |
864 次 |
| 最近记录: |