AcceptHeaderLocaleResolver - 仍然不清楚如何使用它

AcceptHeaderLocaleResolver - still unclear how to use it

我试图在我的应用程序中使用 AcceptHeaderLocaleResolver。我做了很多搜索,但我仍然不明白如何正确使用它。目前,以下代码是有效的:

HeaderLocaleResolver class:

@Component
class HeaderLocaleResolver {

    private val acceptHeaderResolver = AcceptHeaderLocaleResolver()

    init {
        acceptHeaderResolver.defaultLocale = Locale.ENGLISH
    }

    fun getLocale(request: HttpServletRequest): Locale{
        return acceptHeaderResolver.resolveLocale(request)
    }
}

我的休息控制器class:

@RequestMapping("/rest/report")
@RestController
class PrinterController(private val printerService: PrinterService,
                        private val localeResolver: HeaderLocaleResolver) {

    @PostMapping("/{folder}/{templateName}")
    fun printReport(request: HttpServletRequest,
                    @PathVariable("folder") folder : String,
                    @PathVariable("templateName") templateName :String,
                    @RequestParam("doctype") doctype: DocumentType,
                    @RequestBody data: String) : ResponseEntity<InputStreamResource> {
        val locale = localeResolver.getLocale(request)
        val printedReport = printerService.printReport(folder, templateName, doctype, data, locale)
        return ResponseEntity.ok().contentType(printedReport.mediaType)
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; fileName=" + printedReport.filename)
                .body(InputStreamResource(ByteArrayInputStream(printedReport.content)))
    }

}

目前这工作正常,但我不明白的是:我真的必须以这种方式使用 AcceptHeaderLocaleResolver class 吗?我读了很多帖子,展示了如何覆盖 LocalChangeInterceptor 的默认配置,但对我来说 class 需要一个包含 "lang" 参数的 URL 参数,并且然后他决定使用该参数,但我想做的是简单地使用 header。有没有一种方法可以定义一个只从 header 语言读取的拦截器,然后允许您访问该值,也许通过 LocaleContextHolder class?

之前的所有 posts/questions 似乎都缺少一些代码,我尝试了几乎所有代码,但最终都遇到了无效代码或异常。

没关系...我已经用这种方式简单地设置了我的控制器:

@RequestMapping("/rest/report")
@RestController
class PrinterController(private val printerService: PrinterService) {

    @PostMapping("/{folder}/{templateName}", consumes = [MediaType.APPLICATION_JSON_VALUE])
    fun printReport(@RequestHeader(name = "accept-language", defaultValue = "en") lang: String,
                    @PathVariable("folder") folder: String,
                    @PathVariable("templateName") templateName: String,
                    @RequestParam("doctype") doctype: DocumentType,
                    @RequestBody data: String): Mono<ResponseEntity<InputStreamResource>> {
            logger.debug{ "Payload to print: $data in language $lang" }
            return printerService.printReport(folder, templateName, doctype, data, lang)
                .map { report -> ResponseEntity.ok().contentType(report.mediaType)
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; fileName=${report.filename}")
                .body(InputStreamResource(ByteArrayInputStream(report.content))) }
    }

}