【问题标题】:Internationalization by subdomain in Spring BootSpring Boot中子域的国际化
【发布时间】:2015-07-07 20:01:08
【问题描述】:

我正在尝试创建 spring boot(多语言)网络应用程序。

假设来自该域的用户访问:“en.mywebsite.com/index.html” -> 将启动英文语言。

来自该域:“fr.mywebsite.com/index.html” -> 将启动法语语言。

我怎样才能做到这一点?我还查找了this 博客文章,但没有关于子域的其他信息。

【问题讨论】:

  • 写一个特定的LocaleResolver 用于查看完整路径而不是参数、会话或cookie。
  • @M.Deinum 你能给我更具体的例子吗,例如:博客文章、代码 sn-p 等。
  • 有一个接口LocaleResolver,实现resolveLocale方法。它将提取完整的 URL 确定第一部分并使用它来获取Locale。这基本上就是你所需要的......

标签: java spring internationalization subdomain spring-boot


【解决方案1】:

类似下面的方法可以解决问题。

public class SubDomainLocaleResolver extends AbstractLocaleResolver {


    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        String domain = request.getServerName();
        String language = domain.substring(0, domain.indexOf('.'));
        Locale  locale = StringUtils.parseLocaleString(language);
        if (locale == null) {
            locale = determineDefaultLocale(request);
        }
        return locale != null ? locale : determineDefaultLocale(request);
    }

    protected Locale determineDefaultLocale(HttpServletRequest request) {
        Locale defaultLocale = getDefaultLocale();
        if (defaultLocale == null) {
            defaultLocale = request.getLocale();
        }
        return defaultLocale;
    }    

    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
        throw new UnsupportedOperationException("Cannot change sub-domain locale - use a different locale resolution strategy");

    }
}

你得到服务器名称,解析第一部分并尝试解析Locale in none found 你可以得到默认值。

【讨论】:

    猜你喜欢
    • 2016-02-23
    • 1970-01-01
    • 2021-04-17
    • 1970-01-01
    • 2018-12-05
    • 1970-01-01
    • 2018-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多