【问题标题】:How to get Locale in Webflux Functional Endpoints?如何在 Webflux 功能端点中获取语言环境?
【发布时间】:2021-03-23 17:31:40
【问题描述】:

我正在使用 Spring 的 Functional Endpoints 和 Kotlin 来创建 Web 服务,并且我正在尝试找出使用标准 Accept-Language 标头解决 Locale 关闭的惯用方法。

下面是代码的示例:

val repository: PersonRepository = ...
val handler = PersonHandler(repository)

val route = coRouter { 
    GET("/person", handler::getPeople)
}

class PersonHandler(private val repository: PersonRepository) {

    suspend fun getPeople(request: ServerRequest): ServerResponse {
        val locale = /* ??? */
        // create and return response
    }

}

Spring 文档引用使用 LocaleContextResolverLocale 作为请求的一部分进行解析,但在使用功能端点时我看不到使用它的方法。您可以像这样从ServiceRequest.headers().acceptLanguage() 获取传递到Accept-Language 标头的原始 值...

suspend fun getPeople(request: ServerRequest): ServerResponse {
    val locale = 
        Locale.lookup(request.headers().acceptLanguage(), supportedLocales)
        ?: Locale.getDefault()
    // create and return response
}

.. 但这不是在每个 Handler Function 中重新实现LocaleContextResolver 的职责吗?

在 Spring 的功能端点中将 Accept-Language 标头转换为单个/最受支持的 Locale 的惯用方法是什么?

【问题讨论】:

    标签: spring spring-boot kotlin


    【解决方案1】:

    我可以使用before 过滤器做到这一点:

    val repository: PersonRepository = ...
    val handler = PersonHandler(repository)
    
    val route = coRouter { 
        GET("/person", handler::getPeople)
        before(::parseLocale)
    }
    
    fun parseLocale(request: ServerRequest): ServerRequest {
        val locale = try {
            Locale.lookup(request.headers().acceptLanguage(), wellKnownSupportedLocales) ?: wellKnownDefaultLocale
        } catch (exception: RuntimeException) {
            wellKnownDefaultLocale
        }
    
        return ServerRequest
            .from(request)
            .attribute("locale", locale)
            .body(request.bodyToFlux())
            .build()
    }
    
    class PersonHandler(private val repository: PersonRepository) {
    
        suspend fun getPeople(request: ServerRequest): ServerResponse {
            val locale = request.attributes("locale").get() as Locale
            // create and return response
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2020-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多