Spring Boot Localization issue - Accept-Language header

前端 未结 1 711
滥情空心
滥情空心 2021-01-31 06:16

We are using Spring Boot for the application. In ApplicationConfig.java I have the below code

 @Bean
    public LocaleResolver localeResolver() {
        return          


        
相关标签:
1条回答
  • 2021-01-31 07:11

    The solution is:

    public class SmartLocaleResolver extends AcceptHeaderLocaleResolver 
    

    instead of

    public class SmartLocaleResolver extends SessionLocaleResolver
    

    Below is the updated code:

    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;
         }
    }
    

    and in my constants class I have:

    List<Locale> LOCALES = Arrays.asList(new Locale("en"),
                                             new Locale("es"),
                                             new Locale("fr"),
                                             new Locale("es", "MX"),
                                             new Locale("zh"),
                                             new Locale("ja"));
    
    0 讨论(0)
提交回复
热议问题