一尘不染

Spring Boot本地化问题-Accept-Language标头

spring-boot

我们正在为应用程序使用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中的值。

公共静态最终列表LOCALE =集合.unmodifiableList(Arrays.asList(“ en”,“ es”));

我知道在实际情况下,标头将类似于Accept-Language:fr,es; q = 0.8,en-us; q = 0.6,但出于测试目的,我将其传递如下。

接受语言:fr,es,en

代码尚未完成,但是我只是从邮递员那里进行测试,以查看代码是否选择“ es”作为语言环境并给我本地化的结果。

我没有messages_fr.properties文件,但是我有messages_es.properties,因此我希望如果应用程序从下面的代码中设置语言环境,它将选择Locale为’es’并以西班牙语提供所需的值。我需要在此处进行哪些更改才能使代码正常工作?


阅读 1236

收藏
2020-05-30

共1个答案

一尘不染

解决方案是:

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"));
2020-05-30