LocaleResolver

简介(What)

LocaleResolver是SpringMVC定义的基于Web的语言环境策略接口,用于解析当前请求所接收的语言环境,为项目的国际化提供支持。

Definition

Spring 提供了LocaleResolver及其扩展LocaleContextResolver两个接口用于MVC的语言环境解析,两者关系如下图所示:

classDiagram

	class LocaleResolver{
		+resolveLocale(request) Locale
		+setLocale(request,response,locale)
	}
	
	class LocaleContextResolver{
		+resolveLocaleContext(request) LocaleContext
		+setLocaleContext(request,response,localeContext)
	}

	LocaleResolver <|-- LocaleContextResolver

LocaleResolver

LocaleResolver的定义如下:

package org.springframework.web.servlet;

public interface LocaleResolver {
    
    Locale resolveLocale(HttpServletRequest request);

    
    void setLocale(HttpServletRequest request, @Nullable HttpServletResponse response, @Nullable Locale locale);

}

其中,resolveLocale(HttpServletRequest)用于从请求中解析LocalesetLocale(HttpServletRequest,HttpServletResponse,Locale)用于将Locale修改为指定的值。

LocaleContextResolver

LocaleContextResolverLocaleResolver的基础之上,使用LocalContext替代Locale,以实现对更多语言环境变量的支持,如时区TimeZone,其定义如下:

package org.springframework.web.servlet;

public interface LocaleContextResolver extends LocaleResolver {

	LocaleContext resolveLocaleContext(HttpServletRequest request);

	void setLocaleContext(HttpServletRequest request, @Nullable HttpServletResponse response,
			@Nullable LocaleContext localeContext);

}

LocaleContextHolder

LocaleContextHolder是一个基于ThreadLocal的工具类,用于存储由LocaleResolver从请求中解析到的Locale变量及由LocaleContextResolver解析到的LocalContext变量,其核心方法如下:

Init

DispatchServletinitLocaleResolver()方法中,有这样一段代码:

//     public static final String LOCALE_RESOLVER_BEAN_NAME = "localeResolver";
this.localeResolver=context.getBean(LOCALE_RESOLVER_BEAN_NAME,LocaleResolver.class);

LOCALE_RESOLVER_BEAN_NAME的值为localeResolver,想必此刻,小伙伴们应该都明白了自在定义LocaleResolver时, bean的名称为什么必须声明为localeResolver了吧,这就是根本原因所在。

How

CookieLocaleResolver