如何通过 URL 参数(如 ?lang=zh_CN)或 Cookie 实现用户自定义语言切换?

解读

国内项目普遍要求“无刷新切换语言”且“刷新页面后仍保持语言”,同时兼顾 SEO。面试官想确认两点:

  1. 你是否熟悉 Spring Boot + Thymeleaf 的国际化配置链路(LocaleResolver、Interceptor、MessageSource)。
  2. 你是否能在“URL 参数优先”与“Cookie 持久化”之间做权衡,给出可落地的代码级方案,而不是背概念。

知识点

  1. LocaleResolver 体系:AcceptHeaderLocaleResolver、SessionLocaleResolver、CookieLocaleResolver,以及自定义 resolver。
  2. LocaleChangeInterceptor:把 lang 参数绑定到 resolver,实现“点链接即切换”。
  3. MessageSource 配置:basename、encoding、cacheSeconds,确保中文不乱码。
  4. Thymeleaf #{} 语法与 th:lang 属性,保证静态原型能被设计师直接打开。
  5. SameSite、HttpOnly、Path=/ 等 Cookie 安全细节,符合国内等保测评要求。
  6. SEO 场景下,搜索引擎抓取 ?lang=zh_CN 不会导致重复内容,需配合 canonical 或 hreflang。

答案

  1. 配置 MessageSource
@Configuration
public class I18nConfig {
    @Bean
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource ms =
            new ReloadableResourceBundleMessageSource();
        ms.setBasename("classpath:i18n/messages");
        ms.setDefaultEncoding("UTF-8");
        ms.setCacheSeconds(3600);
        return ms;
    }
}

资源文件:
resources/i18n/messages.properties
resources/i18n/messages_zh_CN.properties

  1. 选择“Cookie 持久化 + URL 参数切换”策略
@Configuration
public class LocaleConfig implements WebMvcConfigurer {
    @Bean
    public CookieLocaleResolver localeResolver() {
        CookieLocaleResolver clr = new CookieLocaleResolver();
        clr.setCookieName("lang");
        clr.setCookieMaxAge(3600 * 24 * 30);   // 30 天
        clr.setCookiePath("/");
        clr.setCookieHttpOnly(true);           // 等保要求
        clr.setCookieSecure(false);            // 国内很多站点未全站 HTTPS
        return clr;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
        lci.setParamName("lang");
        registry.addInterceptor(lci);
    }
}
  1. 页面提供入口
<a th:href="@{/home(lang='zh_CN')}">中文</a>
<a th:href="@{/home(lang='en_US')}">English</a>

Thymeleaf 自动读取 resolver 中的 Locale,使用 #{} 输出对应文本:

<title th:text="#{index.title}">默认标题</title>
  1. 验证流程
    首次访问 /home → resolver 未找到 Cookie → 使用 Accept-Language → 返回中文。
    用户点击 “English” → 拦截器把 lang=en_US 写入 Cookie → 后续请求带 Cookie → 无需参数也保持英文。
    SEO 抓取 ?lang=zh_CN 时,后端同样返回对应语言,搜索引擎可索引多语言快照。

拓展思考

  1. 集群部署时,Cookie 方案无状态,无需共享 Session;若客户强制禁用 Cookie,可降级到 URL 重写,Thymeleaf 通过 @{...} 自动追加 ;jsessionid=xxx 或自定义 lang 路径参数,但 URL 丑陋,需权衡。
  2. 为了“域名级”语言,如 en.example.com、zh.example.com,可自定义 LocaleResolver,从 Host 解析,再结合 302 跳转,保持 URL 干净。
  3. 与 Spring Security 整合时,登录页切换语言要放行 /login?lang=xx,否则被过滤器拦截。
  4. 国内微信小程序内嵌 H5,无法写 Cookie,可改用 localStorage + 前端参数回传,后端通过 HandlerMethodArgumentResolver 注入 Locale,实现多端统一。