spring mvc国际化核心是统一管理多语言文本、自动识别用户语言偏好、支持手动切换语言;通过配置messages.properties等资源文件、resourcebundlemessagesource、cookielocaleresolver及localechangeinterceptor实现。

Spring MVC 实现国际化(i18n)的核心在于三件事:统一管理多语言文本、自动识别用户语言偏好、支持手动切换语言。不依赖改代码,只靠配置和约定就能让中英文等多语言并存运行。
准备多语言资源文件
在 src/main/resources 目录下创建命名规范的 .properties 文件:
- messages.properties(默认语言,通常为英文)
- messages_zh_CN.properties(简体中文)
- messages_ja_JP.properties(日语)
- messages_fr_FR.properties(法语)
文件名必须以 basename + 下划线 + 语言_国家 形式命名,语言代码用 ISO 639(如 zh、en),国家代码用 ISO 3166(如 CN、US)。内容按 key=value 格式写,例如:
login.title=Login Page<br>login.username=Username<br>login.password=Password<br><br>login.title=登录页面<br>login.username=用户名<br>login.password=密码
配置 MessageSource 加载资源
这是读取多语言文本的“翻译引擎”。推荐使用 ResourceBundleMessageSource,Java 配置示例如下:
- 设置 basename 为
messages(对应文件前缀) - 指定 defaultEncoding 为 UTF-8,避免中文乱码
- 开启 useCodeAsDefaultMessage(true),找不到翻译时直接返回 key,便于排查遗漏
示例代码:
@Bean<br>public MessageSource messageSource() {<br> ResourceBundleMessageSource source = new ResourceBundleMessageSource();<br> source.setBasename("messages");<br> source.setDefaultEncoding("UTF-8");<br> source.setUseCodeAsDefaultMessage(true);<br> return source;<br>}配置 LocaleResolver 确定当前语言
它决定每次请求该用哪种语言。常用两种方式:
- CookieLocaleResolver:把用户选择的语言存在 Cookie 里,跨请求持久,适合记住用户偏好
- SessionLocaleResolver:存在 Session 中,关闭浏览器即失效,更轻量
推荐 Cookie 方式,配置时可指定 Cookie 名(如 lang)、默认语言(如 Locale.ENGLISH):
@Bean<br>public LocaleResolver localeResolver() {<br> CookieLocaleResolver resolver = new CookieLocaleResolver();<br> resolver.setCookieName("lang");<br> resolver.setDefaultLocale(Locale.ENGLISH);<br> resolver.setCookieMaxAge(60 * 60 * 24 * 30); // 30天<br> return resolver;<br>}启用语言切换能力
光有识别还不够,得让用户能点一下就换语言。Spring 提供了开箱即用的 LocaleChangeInterceptor:
- 拦截请求,检查是否带
?lang=zh_CN这类参数 - 自动更新当前 Locale,并写入 Cookie 或 Session
- 注册到 WebMvcConfigurer 的拦截器链即可生效
配置示例:
@Bean<br>public LocaleChangeInterceptor localeChangeInterceptor() {<br> LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor();<br> interceptor.setParamName("lang"); // 对应 URL 参数名<br> return interceptor;<br>}<br><br>@Override<br>public void addInterceptors(InterceptorRegistry registry) {<br> registry.addInterceptor(localeChangeInterceptor());<br>}之后访问 /login?lang=zh_CN 就会切到中文,且后续请求自动沿用该语言,直到再次切换或 Cookie 过期。
视图层用 <message code="login.username"></message>,控制器里用 messageSource.getMessage("login.title", null, locale) —— 文本自动匹配当前语言。日期、数字格式也能通过 spring:eval 或 fmt:formatDate 做本地化渲染。











