spring - Spring WebFlux 中的 SessionLocaleResolver 等效项 - 通过会话数据解析语言环境
问题描述
如果我们需要从会话数据中解析语言环境值,我们如何在 Spring WebFlux 中以响应式的方式实现呢?
对于非反应式 Web 应用程序,SessionLocaleResolver
可用于从会话数据中解析语言环境。
对于 Spring WebFlux,拦截语言环境解析器的方法是使用LocaleContextResolver
. Spring Boot WebFlux starter 中提供的默认实现是AcceptHeaderLocaleContextResolver
. 这个接口的问题是它只提供了同步方法resolveLocaleContext(ServerWebExchange)
。如果我需要从请求查询参数或Accept-Language
标头中解析语言环境,它可以完美运行,因为ServerWebExchange
它提供了访问请求对象的直接方法,而请求对象又提供了直接访问参数和标头的方法。
override fun resolveLocaleContext(exchange: ServerWebExchange): LocaleContext {
val langParams = exchange.request.queryParams["lang"]
var targetLocale: Locale? = null
if (langParams != null && langParams.isNotEmpty()) {
for (lang in langParams) {
val locale = Locale.forLanguageTag(lang)
if (locale != null) {
targetLocale = locale
break
}
}
}
return SimpleLocaleContext(targetLocale ?: Locale.forLanguageTag("en-US"))
}
但是,如果我需要从会话数据中解析语言环境,就会出现问题。ServerWebExchange#getSession()
返回Mono<WebSession>
。除非我调用Mono#block()
. 然而,这不是一种理想的、被动的方式。
有没有办法解决这个问题?或者春天有什么计划来改变这个吗?
(之前有一个类似的问题被埋没了:Spring WebFlux - SessionLocaleResolver)
解决方案
推荐阅读
- html - 单击时旋转字体真棒 90 图标
- prestashop - Prestashop 类别价格
- r - R markdown 代码显示我不想要的输出,我该如何删除它?
- reactjs - 根据当前 URL 更改链接的 className,React
- javascript - 在 Acrobat Pro 中使用 Javascript 更改日期格式
- c - c程序中使用指针的函数和数组
- c++ - QDate 从/到字符串的转换不一致(世纪问题)
- r - 未使用的参数(family = 二项式)
- android - Android - 导航后观察不起作用
- python - 如何确定动画 GIF 帧中透明像素的数量?