【问题标题】:Spring MVC for Rest: How set a Locale valueSpring MVC for Rest:如何设置语言环境值
【发布时间】:2018-02-15 05:36:54
【问题描述】:

我正在使用 Spring Framework 4.3.2

关于Rest对于POSTPUT会出现以下情况。

对于POST,我有以下内容:

@PostMapping(consumes={MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_UTF8_VALUE})
public ResponseEntity<Void> saveOne(@Validated @RequestBody Persona persona){

观察方法声明了@Validated

我需要根据客户端/用户发送的Locale 进行验证并返回错误文本消息。

我可以通过Spring MVC Test 做到这一点,因为我有以下几点:

resultActions = mockMvc.perform(post(uri).contentType(MediaType.APPLICATION_XML)
                     .accept(MediaType.APPLICATION_XML)
                     .locale(locale)
                     .content(...content...))).andDo(print());

观察.locale(locale) 部分。

直到这里关于JUnit@Parameters 我能够发送Locales 的列表,因此可以看到不同语言的错误消息。直到这里一切都按预期进行

现在,访问 Rest 控制器的另一种方法是通过 RestTemplate

我有以下:

RequestEntity<Persona> requestEntity = RequestEntity.post(uri)
               .contentType(MediaType.APPLICATION_JSON_UTF8)
               .accept(MediaType.APPLICATION_JSON_UTF8)                                                               
               .body(personaValid);

....

ResponseEntity<GenericCollection<ValidatedFieldErrorReport>> responseEntity_ 
  = restTemplate.exchange(requestEntity, parameterizedTypeReference);

遗憾的是RequestEntity通过post不支持.locale(locale)

即使我添加.header("Accept-Language", locale.toString()),它也不起作用,.header("locale", locale.toString()) 的考虑相同。

注意:我可以确认,当我打印 RequestEntity 对象时,它会在服务器中发送预期的 Locale :它忽略了发送的“语言环境” (如果它从来没有从一开始就被发送过)并使用服务器中可用的默认Locale。我对这种方法感到困惑。

我想保留 RequestEntityResponseEntity 对象。他们的 API 很流畅。

因此,正确的方法是什么?我的印象是客户端或服务器中的额外配置在某些地方需要它。

【问题讨论】:

  • 你在服务器端配置了哪个区域解析器?
  • 我只定义了 @Beans 和 LocaleChangeInterceptorSessionLocaleResolvernew Locale("en","US")registry.addInterceptor(localeChangeInterceptorConfig.localeChangeInterceptor()) 的方式。根据您的问题,似乎缺少@Bean
  • 所以你的解析器总是返回new Locale("en","US")?你想知道为什么发送Accept-Language 标头没有效果?
  • 服务器总是只打印en。看来我需要在服务器端定义一个@Bean
  • 看来我不够明确。你得到en,因为你有new Locale("en","US")。选择合适的语言环境解析器。

标签: spring spring-mvc resttemplate spring-mvc-test


【解决方案1】:

对于RequestEntity,您应该使用:

.header(HttpHeaders.ACCEPT_LANGUAGE, locale.toLanguageTag());

【讨论】:

    猜你喜欢
    • 2011-09-20
    • 1970-01-01
    • 2013-05-24
    • 2014-09-15
    • 2019-08-27
    • 2019-08-27
    • 1970-01-01
    • 1970-01-01
    • 2010-09-09
    相关资源
    最近更新 更多