i18n拦截器源代码详解
public Stringintercept(ActionInvocation invocation) throws Exception {
if (LOG.isDebugEnabled()) {
LOG.debug("intercept '#0/#1' {",
invocation.getProxy().getNamespace(),invocation.getProxy().getActionName());
}
LocaleFinder localeFinder = new LocaleFinder(invocation);
Locale locale =getLocaleFromParam(localeFinder.getRequestedLocale());
locale = storeLocale(invocation,locale, localeFinder.getStorage());
saveLocale(invocation, locale);
if (LOG.isDebugEnabled()) {
LOG.debug("before Locale=#0", invocation.getStack().findValue("locale"));
}
final String result = invocation.invoke();
if (LOG.isDebugEnabled()) {
LOG.debug("after Locale=#0", invocation.getStack().findValue("locale"));
LOG.debug("intercept } ");
}
return result;
}
///从LocaleFinder开始看:
其构造函数如下:
protected LocaleFinder(ActionInvocationinvocation) {
actionInvocation = invocation;
find();
}
再来看find()函数:
protected void find() {
//get requested locale
获得参数map
Map<String, Object> params = actionInvocation.getInvocationContext().getParameters();
///设置storage已用后面的函数是否在session中存储该locale作依据
storage = Storage.SESSION.toString();
/parameterName是字符串常量,为:”request_locale” requestedLocale为object;
requestedLocale = findLocaleParameter(params, parameterName);
if (requestedLocale != null) {
return;
}
//如果用”request_locale”没有获得,则用"request_only_locale"获得并把storage赋为Storage.NONE
requestedLocale = findLocaleParameter(params, requestOnlyParameterName);
if (requestedLocale != null) {
storage = Storage.NONE.toString();
}
}
//find()结束返回I18nInterceptor.Intercept()中执行getLocaleFromParam(localeFinder.getRequestedLocale())函数并返回Locale对象
///重点看storeLocale()函数:
protectedLocale storeLocale(ActionInvocationinvocation, Locale locale, String storage) {
//save it in session
//获得sessionmap
Map<String, Object> session =invocation.getInvocationContext().getSession();
if (session != null) {
synchronized (session) {
/如果locale为null则通过session或游览器的方式获得locale,并把storage设为Storage.NONE,也就是说只有参数为:request_only_locale或没有参数时,locale是不存储在session中的。
if (locale == null) {
storage = Storage.NONE.toString();
//从该函数读取session或游览器的默认语言环境Locale。
locale =readStoredLocale(invocation, session);解释在最后面。
}
//当Storage== SESSION是将locale存储在session中
if (Storage.SESSION.toString().equals(storage)) {
session.put(attributeName, locale);
}
}
}
return locale;
}
执行完成返回locale。
在通过该函数讲locale保存在context中saveLocale(invocation, locale)
protectedLocale readStoredLocale(ActionInvocation invocation, Map<String, Object>session) {
//通过session获得locale对象。如果没有获得则从context中获取。
Locale locale = this.readStoredLocalFromSession(invocation,session);
if (locale != null) {
return locale;
}
return this.readStoredLocalFromCurrentInvocation(invocation);
}