[英]Access Struts2 locale in Spring AbstractRoutingDataSource
Our application uses Struts2 Internalization and Spring AbstractRoutingDataSource
for dynamic database changes. 我们的应用程序使用Struts2内部化和Spring AbstractRoutingDataSource
进行动态数据库更改。 Changing the language, the corresponding language database should be selected. 更改语言后,应选择相应的语言数据库。
So the below code makes the dynamic database selection using Spring RoutingDataSource
. 因此,以下代码使用Spring RoutingDataSource
进行动态数据库选择。
public class RoutingDataSource extends AbstractRoutingDataSource {
protected Object determineCurrentLookupKey() {
return LanguageContextHolder.getLanguagetype();
}
}
Spring RoutingDataSource
is working fine. Spring RoutingDataSource
工作正常。
My problem is how to set the locale on change. 我的问题是如何在更改时设置语言环境。 Since it is stored in Struts2, I am not able to access it in Spring. 由于它存储在Struts2中,因此我无法在Spring中访问它。
I found the Spring MVC org.springframework.context.i18n.LocaleContextHolder
would do this, but since we are using Struts2, how can I do the above? 我发现Spring MVC org.springframework.context.i18n.LocaleContextHolder
可以做到这一点,但是由于我们使用的是Struts2,我该如何做?
Struts2 stores current locale in session with default key WW_TRANS_I18N_LOCALE
. Struts2使用默认键WW_TRANS_I18N_LOCALE
在会话中存储当前语言环境。 To access session inside your RoutingDataSource
use ActionContext.getContext().getSession()
method. 要访问RoutingDataSource
内部的会话,请使用ActionContext.getContext().getSession()
方法。
// ...
if (ActionContext.getContext() != null) {
Map<String, Object> session = ActionContext.getContext().getSession();
if (session != null && session.containsKey(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)) {
Locale locale = (Locale) session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE);
}
}
// ...
In my example above "return LanguageContextHolder.getLanguagetype();" 在上面的示例中,“返回LanguageContextHolder.getLanguagetype();” will return ThreadLocal type. 将返回ThreadLocal类型。 And it is implemented as below. 并实现如下。
public class LanguageContextHolder implements Serializable {
private static ThreadLocal<LanguageType> languageType = new ThreadLocal<LanguageType>();
public static ThreadLocal<LanguageType> getLanguagetype() {
return languageType;
}
public static void setLanguagetype(ThreadLocal<LanguageType> languagetype) {
languageType = languagetype;
}
public static void clearLanguageType() {
languageType.remove();
}
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.