2016-09-19 56 views
2

我與Spring框架的工作4.3.2Spring MVC的休息:如何設置一個區域值

關於RestPOSTPUT下面的情況發生。

對於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我能夠發送一個Locale s列表,從而看到不同語言的錯誤消息。直到這裏都去如何有望

現在,其他的方式來訪問一個休息控制器通過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流利。

因此,什麼是正確的方法?我的印象是客戶端或服務器的額外配置在某個地方需要它。

+0

哪些本地化解析器,你已經在服務器端配置? – zeroflagL

+0

我只定義了'@ Bean'是如何用locale(「en」,「US」)和registry.addInterceptor(localeChangeInterceptorConfig.localeChangeInterceptor())'調用'LocaleChangeInterceptor'和'SessionLocaleResolver'的。根據你的問題,似乎缺少一個「@ Bean」 –

+0

所以你的解析器總是返回'新Locale(「en」,「US」)'?你想知道爲什麼發送'Accept-Language'頭文件沒有效果? – zeroflagL

回答

0

對於RequestEntity你應該使用:

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