我们正在使用Spring Boot作为应用程序。在ApplicationConfig.java中,我有以下代码
@Bean
public LocaleResolver localeResolver() {
return new SmartLocaleResolver();
}
,SmartLocaleResolver.java位于
之下public class SmartLocaleResolver extends SessionLocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest request) {
final String acceptLanguage = request.getHeader("Accept-Language");
if (acceptLanguage.contains(",")) {
String[] aheader = acceptLanguage.split(",[ ]*");
for (String locale : aheader) {
if (ApplicationConstants.LOCALE.contains(locale)) {
locale.trim();
return Locale.forLanguageTag(locale);
}
}
} else if (!acceptLanguage.contains(",") && !acceptLanguage.isEmpty()) {
if (ApplicationConstants.LOCALE.contains(acceptLanguage)) {
return Locale.forLanguageTag(acceptLanguage);
}
}
return request.getLocale();
}
}
我在下面的常量类中比较了标题Accept-Language的值。
public static final List LOCALE = Collections .unmodifiableList(Arrays.asList(" en"," es"));
我知道在实际情况下标题会是这样的 Accept-Language:fr,es; q = 0.8,en-us; q = 0.6但是出于测试目的,我将其传递如下。
接受语言:fr,es,en
代码尚未完成,但我只是从邮递员那里进行测试,看看代码是否已经完成了#34; es"作为语言环境,并给我本地化的结果。
我没有messages_fr.properties文件,但我有messages_es.properties,所以我希望如果应用程序从下面的代码设置区域设置,它会选择Locale作为' es'并用西班牙语给出我想要的价值观。我需要在这里进行哪些更改才能使代码生效?
答案 0 :(得分:15)
解决方案是:
public class SmartLocaleResolver extends AcceptHeaderLocaleResolver
而不是
public class SmartLocaleResolver extends SessionLocaleResolver
以下是更新的代码:
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Locale;
import com.bbtransact.tss.api.commons.http.HttpConstants;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;
public class SmartLocaleResolver extends AcceptHeaderLocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest request) {
if (StringUtils.isBlank(request.getHeader("Accept-Language"))) {
return Locale.getDefault();
}
List<Locale.LanguageRange> list = Locale.LanguageRange.parse(request.getHeader("Accept-Language"));
Locale locale = Locale.lookup(list, ApplicationConstants.LOCALES);
return locale;
}
}
在我的常规课中我有:
List<Locale> LOCALES = Arrays.asList(new Locale("en"),
new Locale("es"),
new Locale("fr"),
new Locale("es", "MX"),
new Locale("zh"),
new Locale("ja"));