Ste*_*ane 6 rest spring locale
我正在尝试在Spring 3 REST应用程序中处理区域设置更改.
但是语言环境没有改为fr.
控制台日志显示:2014-05-19 14:29:46,214 DEBUG [AbstractExceptionHandler] locale:en
这是我的配置:
@Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasenames("classpath:messages/messages", "classpath:messages/validation");
// If true, the key of the message will be displayed if the key is not found, instead of throwing an exception
messageSource.setUseCodeAsDefaultMessage(true);
messageSource.setDefaultEncoding("UTF-8");
// The value 0 means always reload the messages to be developer friendly
messageSource.setCacheSeconds(0);
return messageSource;
}
// The locale interceptor provides a way to switch the language in any page just by passing the lang=’en’, lang=’fr’, and so on to the url
@Override
public void addInterceptors(InterceptorRegistry registry) {
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("lang");
registry.addInterceptor(localeChangeInterceptor);
}
@Bean
public LocaleResolver localeResolver() {
CookieLocaleResolver localeResolver = new CookieLocaleResolver();
localeResolver.setDefaultLocale(new Locale("en"));
return localeResolver;
}
Run Code Online (Sandbox Code Playgroud)
这是我的异常处理程序:
@ControllerAdvice
public class AdminExceptionHandler extends AbstractExceptionHandler {
@ExceptionHandler(NullPointerException.class)
@ResponseBody
public ResponseEntity<ErrorInfo> nullPointerException(HttpServletRequest request, NullPointerException e) {
String url = request.getRequestURL().toString();
String errorMessage = localizeErrorMessage("error.npe", new Object[] { e.getMessage() });
return new ResponseEntity<ErrorInfo>(new ErrorInfo(url, errorMessage), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
public class AbstractExceptionHandler {
private static Logger logger = LoggerFactory.getLogger(AbstractExceptionHandler.class);
@Autowired
private MessageSource messageSource;
protected String localizeErrorMessage(String errorCode, Object args[]) {
Locale locale = LocaleContextHolder.getLocale();
logger.debug("locale: " + locale);
return messageSource.getMessage(errorCode, args, locale);
}
protected String localizeErrorMessage(String errorCode) {
return localizeErrorMessage(errorCode, null);
}
protected String extractAdminIdFromUrl(String url) {
String adminId = null;
try {
URI uri = new URI(url);
String path = uri.getPath();
adminId = path.substring(path.lastIndexOf('/') + 1);
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
return adminId;
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的测试:
@Test
public void testExceptionLocalizedMessage() throws Exception {
HttpHeaders httpHeaders = Common.createAuthenticationHeaders("stephane" + ":" + PASSWORD);
MvcResult resultGet = this.mockMvc.perform(
get("/error/npe").headers(httpHeaders)
.param("lang", "fr")
.accept(MediaType.APPLICATION_JSON)
)
.andExpect(status().isInternalServerError())
.andExpect(jsonPath("$.message").value("Une erreur inconnue s'est produite. Veuillez nous excuser."))
.andReturn();
httpHeaders.add("Accept-Language", "fr");
resultGet = this.mockMvc.perform(
get("/error/npe").headers(httpHeaders)
.accept(MediaType.APPLICATION_JSON)
)
.andExpect(status().isInternalServerError())
.andExpect(jsonPath("$.message").value("Une erreur inconnue s'est produite. Veuillez nous excuser."))
.andReturn();
}
Run Code Online (Sandbox Code Playgroud)
我想处理url中的locale参数,如?lang = en和Accept-Language标题作为后退.
作为REST应用程序,我考虑使用AcceptHeaderLocaleResolver类,但它不支持通过url参数设置语言环境.
我估计在REST应用程序中使用SessionLocaleResolver类没什么意义.
这使我得到了CookieLocaleResolver类,我并不特别相信它是应该在REST应用程序中使用的类.
无论如何,检索到的语言环境仍然是en而不是我期望的那样.
编辑:
在测试中,使用语句:
httpHeaders.add("Accept-Language", Locale.FRENCH.getLanguage());
Run Code Online (Sandbox Code Playgroud)
不设置区域设置.但是使用locale()可以.该测试通过:
this.mockMvc.perform(
get("/error/npe").headers(httpHeaders).locale(Locale.FRENCH)
.accept(MediaType.APPLICATION_JSON))
.andDo(print()
)
.andExpect(status().isInternalServerError())
.andExpect(jsonPath("$.message").value(localizeErrorMessage("error.npe", Locale.FRENCH)))
.andReturn();
Run Code Online (Sandbox Code Playgroud)
我找到了解决方案.现在正在使用Accept-Language标头和cookie.
public class WebConfiguration extends WebMvcConfigurerAdapter {
@Bean
public LocaleResolver localeResolver() {
return new SmartLocaleResolver();
}
}
public class SmartLocaleResolver extends CookieLocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest request) {
String acceptLanguage = request.getHeader("Accept-Language");
if (acceptLanguage == null || acceptLanguage.trim().isEmpty()) {
return super.determineDefaultLocale(request);
}
return request.getLocale();
}
}
Run Code Online (Sandbox Code Playgroud)
更新:在Thor的评论之后,这是一个首先检查cookie的解析器,如果没有找到,则检查请求头:
@Override
public Locale resolveLocale(HttpServletRequest request) {
Locale locale = super.determineDefaultLocale(request);
if (null == locale) {
String acceptLanguage = request.getHeader("Accept-Language");
if (acceptLanguage != null && !acceptLanguage.trim().isEmpty()) {
locale = request.getLocale();
}
}
return locale;
}
Run Code Online (Sandbox Code Playgroud)
或者使用更简单的实现(未测试):
private AcceptHeaderLocaleResolver acceptHeaderLocaleResolver = new AcceptHeaderLocaleResolver();
@Override
public Locale resolveLocale(HttpServletRequest request) {
Locale locale = super.determineDefaultLocale(request);
if (null == locale) {
locale = acceptHeaderLocaleResolver.resolveLocale(request);
}
return locale;
}
Run Code Online (Sandbox Code Playgroud)
更新:以上解决方案不再有效.
我现在正试图在标题中传递接受的语言:
httpHeaders.add(HttpHeaders.ACCEPT_LANGUAGE, "fr_FR");
Run Code Online (Sandbox Code Playgroud)
并在此语言环境解析器中检索它:
@Override
public Locale resolveLocale(HttpServletRequest request) {
for (String httpHeaderName : Collections.list(request.getHeaderNames())) {
logger.debug("===========>> Header name: " + httpHeaderName);
}
String acceptLanguage = request.getHeader(HttpHeaders.ACCEPT_LANGUAGE);
logger.debug("===========>> acceptLanguage: " + acceptLanguage);
Locale locale = super.resolveLocale(request);
logger.debug("===========>> acceptLanguage locale: " + locale.getDisplayCountry());
if (null == locale) {
locale = getDefaultLocale();
logger.debug("===========>> Default locale: " + locale.getDisplayCountry());
}
return locale;
}
Run Code Online (Sandbox Code Playgroud)
但是记录器Accept-Language
的输出中没有===========>> Header name
,并且acceptLanguage
记录器是空的.
归档时间: |
|
查看次数: |
7502 次 |
最近记录: |