我在Spring MVC中遇到i18n问题。当我调用此方法来获取当前语言环境时:
public static final Locale DEFAULT_LOCALE = new Locale("en", "GB");
public Locale getLocale() {
if (RequestContextHolder.getRequestAttributes() != null) {
final HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
.getRequestAttributes()).getRequest();
final LocaleResolver localeResolver = RequestContextUtils
.getLocaleResolver(request);
if (localeResolver != null) {
Locale locale = localeResolver.resolveLocale(request);
if (locale != null) {
return locale;
}
}
}
return DEFAULT_LOCALE;
}
它返回正确的语言环境但没有设置国家/地区属性。
public String getCurrency() {
Locale locale = getLocale();
System.err.println("Locale: " + getLocale());
String country = locale.getCountry();
System.err.println("Country: " + country);
String displayCountry = locale.getDisplayCountry();
System.err.println("displayCountry: " + displayCountry);
String displayName = locale.getDisplayName();
System.err.println("displayName: " + displayName);
Currency currency = Currency.getInstance(locale);
System.err.println("Currency.getSymbol() = " + currency.getSymbol());
return currency.getSymbol();
}
此方法打印:
Locale: ro
Country:
displayCountry:
displayName: Romanian
我实际上需要获取区域设置货币,但这会调用Currency.getInstance(locale);抛出java.lang.IllegalArgumentException,因为country属性为空。
这是我用于国际化的配置文件:
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="en" />
</bean>
<mvc:interceptors>
<bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang" />
</bean>
</mvc:interceptors>
我认为问题在于,当我选择一个新国家时,它只会改变语言。
以下是我更改语言的地方:
<a class="country_flag" href="?lang=uk">United Kingdom</a>
<a class="country_flag" href="?lang=ro">Romania</a>
答案 0 :(得分:0)
我使用SessionLocaleResolver,它对我有用:
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="ru_RU" />
</bean>
注意 - 值应为xx_XX,尽管jsp中的lang = xx:
<li><a href="?lang=en"><img src="<c:url value="/resources/languages/en.png"/>" border="0"/></li>
<li><a href="?lang=ru"><img src="<c:url value="/resources/languages/ru.png"/>" border="0"/></li>