Spring MVC 国际化 (i18n) 与本地化 (L10n) 实战指南:多语言支持与区域适配

这是文章《Spring MVC 国际化(i18n)和本地化(L10n)示例》的第1部分(共3部分)。

欢迎来到 Spring 国际化(i18n)教程。对于任何面向全球用户的 Web 应用程序而言,国际化(i18n)或本地化(L10n)对于提升用户互动体验至关重要。大多数 Web 应用程序框架都提供了根据用户区域设置来本地化应用程序的简便方法。Spring 也遵循这一模式,通过使用 Spring 拦截器、区域解析器和不同区域的资源包,提供了广泛的国际化(i18n)支持。以下是关于 Java 中国际化的一些早期文章:

  • Java 国际化示例
  • Struts2 国际化示例

Spring 国际化(i18n)

让我们创建一个简单的 Spring MVC 项目,在该项目中,我们将使用请求参数来获取用户的区域设置,并根据此设置从特定于区域设置的资源包中设置响应页面的标签值。在 Spring Tool Suite (STS) 中创建一个 Spring MVC 项目,以获取我们应用程序的基本代码。如果您对 Spring Tool Suite 或 Spring MVC 项目不熟悉,请阅读 Spring MVC 示例。我们最终的本地化项目更改如下图所示。我们将逐一研究应用程序的所有部分。

Spring 国际化 Maven 配置

我们的 Spring MVC 项目的 pom.xml 文件如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.Olivia</groupId>
	<artifactId>spring</artifactId>
	<name>Springi18nExample</name>
	<packaging>war</packaging>
	<version>1.0.0-BUILD-SNAPSHOT</version>
	<properties>
		<java-version>1.6</java-version>
		<org.springframework-version>4.0.2.RELEASE</org.springframework-version>
		<org.aspectj-version>1.7.4</org.aspectj-version>
		<org.slf4j-version>1.7.5</org.slf4j-version>
	</properties>
	<dependencies>
		<!-- Spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${org.springframework-version}</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				 </exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
				
		<!-- AspectJ -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>${org.aspectj-version}</version>
		</dependency>	
		
		<!-- Logging -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${org.slf4j-version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.15</version>
			<exclusions>
				<exclusion>
					<groupId>javax.mail</groupId>
					<artifactId>mail</artifactId>
				</exclusion>
				<exclusion>
					<groupId>javax.jms</groupId>
					<artifactId>jms</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jdmk</groupId>
					<artifactId>jmxtools</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jmx</groupId>
					<artifactId>jmxri</artifactId>
				</exclusion>
			</exclusions>
			<scope>runtime</scope>
		</dependency>

		<!-- @Inject -->
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
		</dependency>
				
		<!-- Servlet -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
	
		<!-- Test -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.7</version>
			<scope>test</scope>
		</dependency>        
	</dependencies>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <additionalProjectnatures>
                        <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
                    </additionalProjectnatures>
                    <additionalBuildcommands>
                        <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
                    </additionalBuildcommands>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <compilerArgument>-Xlint:all</compilerArgument>
                    <showWarnings>true</showWarnings>
                    <showDeprecation>true</showDeprecation>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <configuration>
                    <mainClass>org.test.int1.Main</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

大部分代码由 STS 自动生成,我只将 Spring 版本更新到了最新的 4.0.2.RELEASE。我们也可以删除或更新其他依赖项的版本,但为了简单起见,我保持其不变。

Spring 资源包

这是文章《Spring MVC 国际化(i18n)和本地化(L10n)示例》的第2部分(共3部分)。

为了简化,我们假设应用程序只支持两种语言环境:英语和法语。如果用户未指定语言环境,我们将默认使用英语。我们将为这两种语言环境创建Spring资源包,用于JSP页面。

messages_en.properties 代码:

label.title=Login Page
label.firstName=First Name
label.lastName=Last Name
label.submit=Login

messages_fr.properties 代码:

label.title=Connectez-vous page
label.firstName=Pr\u00E9nom
label.lastName=Nom
label.submit=Connexion

请注意,我在法语资源包中使用了Unicode对特殊字符进行编码,以确保在响应HTML发送给客户端请求时能够正确解析。另一个重要的注意事项是,这些资源包都位于应用程序的类路径中,并且它们的命名遵循“messages_{locale}.properties”的模式。我们将在稍后看到这些为何重要。

Spring i18n 控制器类

我们的控制器类非常简单,它只记录用户的语言环境,并返回 home.jsp 页面作为响应。

package com.Olivia.spring;

import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
	
		return "home";
	}
	
}

Spring i18n JSP 页面

我们的 home.jsp 页面代码如下所示。

<%@taglib uri="https://www.springframework.org/tags" prefix="spring"%>
<%@ page session="false"%>
<html>
<head>
<title><spring:message code="label.title" /></title>
</head>
<body>
	<form method="post" action="login">
		<table>
			<tr>
				<td><label> <strong><spring:message
								code="label.firstName" /></strong>
				</label></td>
				<td><input name="firstName" /></td>
			</tr>
			<tr>
				<td><label> <strong><spring:message
								code="label.lastName" /></strong>
				</label></td>
				<td><input name="lastName" /></td>
			</tr>
			<tr>
				<spring:message code="label.submit" var="labelSubmit"></spring:message>
				<td colspan="2"><input type="submit" value="${labelSubmit}" /></td>
			</tr>
		</table>
	</form>
</body>
</html>

唯一值得一提的部分是使用 <spring:message> 标签根据给定的代码检索消息。请确保使用 taglib JSP 指令配置了 Spring 标签库。Spring 负责加载适当的资源包消息,并使其可供 JSP 页面使用。

Spring 国际化 – Bean 配置文件

这是文章《Spring MVC 国际化(i18n)和本地化(L10n)示例》的第3部分(共3部分)。

Spring Bean 配置文件是所有“魔法”发生的地方。这正是 Spring 框架的魅力所在,它帮助我们更专注于业务逻辑,而不是为琐碎的任务编写代码。让我们看看我们的 Spring Bean 配置文件是什么样的,然后我们会逐一查看每个 Bean。

servlet-context.xml 代码:

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="https://www.springframework.org/schema/mvc"
	xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns:beans="https://www.springframework.org/schema/beans"
	xmlns:context="https://www.springframework.org/schema/context"
	xsi:schemaLocation="https://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
		https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
		https://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

	<!-- DispatcherServlet 上下文:定义此 Servlet 的请求处理基础设施 -->

	<!-- 启用 Spring MVC @Controller 编程模型 -->
	<annotation-driven />

	<!-- 通过高效地提供 ${webappRoot}/resources 目录中的静态资源来处理 /resources/** 的 HTTP GET 请求 -->
	<resources mapping="/resources/**" location="/resources/" />

	<!-- 将 @Controllers 选择用于渲染的视图解析为 /WEB-INF/views 目录中的 .jsp 资源 -->
	<beans:bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>

	<beans:bean id="messageSource"
		class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
		<beans:property name="basename" value="classpath:messages" />
		<beans:property name="defaultEncoding" value="UTF-8" />
	</beans:bean>

	<beans:bean id="localeResolver"
		class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
		<beans:property name="defaultLocale" value="en" />
		<beans:property name="cookieName" value="myAppLocaleCookie"></beans:property>
		<beans:property name="cookieMaxAge" value="3600"></beans:property>
	</beans:bean>

	<interceptors>
		<beans:bean
			class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
			<beans:property name="paramName" value="locale" />
		</beans:bean>
	</interceptors>

	<context:component-scan base-package="com.Olivia.spring" />

</beans:beans>
  1. 通过注解驱动的标签来启用控制器编程模型,如果没有它,Spring 将不会将我们的 HomeController 识别为客户端请求的处理程序。

上下文扫描提供了 Spring 将查找注解组件并自动将其注册为 Spring Bean 的包。

配置了 messageSource Bean,以为我们的应用启用国际化。basename 属性用于提供资源包的位置。classpath:messages 表示资源包位于类路径中,并且遵循名称模式 messages_{locale}.propertiesdefaultEncoding 属性用于定义用于消息的编码方式。

使用 org.springframework.web.servlet.i18n.CookieLocaleResolver 类型的 localeResolver Bean,可以在客户端请求中设置 Cookie,以便后续请求可以轻松地识别用户的语言环境。例如,我们可以在用户首次启动 Web 应用程序时要求用户选择语言环境,并且借助 Cookie,我们可以识别用户的语言环境并自动发送特定语言的响应。我们还可以指定默认语言环境、Cookie 名称和 Cookie 过期和删除之前的最长时间。如果应用程序维护用户会话,则还可以使用 org.springframework.web.servlet.i18n.SessionLocaleResolver 作为 localeResolver,以在用户会话中使用语言环境属性。其配置与 CookieLocaleResolver 类似。

如果我们没有注册任何 localeResolver,默认情况下将使用 AcceptHeaderLocaleResolver,它通过检查客户端 HTTP 请求中的 accept-language 标头来确定用户的语言环境。

配置了 org.springframework.web.servlet.i18n.LocaleChangeInterceptor 拦截器,用于拦截用户请求并识别用户的语言环境。参数名称是可配置的,我们使用的是名为“locale”的请求参数名称作为语言环境。如果没有这个拦截器,我们将无法更改用户的语言环境并根据用户的新语言环境设置发送响应。它需要作为 interceptors 元素的一部分,否则 Spring 将不会将其配置为拦截器。

如果你对告诉 Spring 框架加载我们的上下文配置文件的配置感到困惑,这个配置位于我们的 MVC 应用程序部署描述符中。

<servlet>
	<servlet-name>appServlet</servlet-name>
	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	<init-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
	</init-param>
	<load-on-startup>1</load-on-startup>
</servlet>
		
<servlet-mapping>
	<servlet-name>appServlet</servlet-name>
	<url-pattern>/</url-pattern>
</servlet-mapping>

我们可以通过更改 web.xml 配置来改变上下文文件的位置或名称。我们的 Spring i18n 应用程序已经准备好了,只需要在任何 Servlet 容器中部署它。通常情况下,我将其导出为 WAR 文件,放在独立的 Tomcat Web 服务器的 webapps 目录下。下面是我们应用程序主页在不同语言环境下的截图。

默认主页(英语环境):

传递语言环境作为参数(法语环境):

没有指定语言环境的进一步请求:

从上面的图像可以看出,我们在客户端请求中没有传递语言环境信息,但我们的应用程序仍然可以识别用户的语言环境。你可能已经猜到了,这是因为我们在 Spring Bean 配置文件中配置了 CookieLocaleResolver Bean。不过,你可以检查浏览器的 Cookie 数据来确认这个情况。我正在使用 Chrome 浏览器,下面的图片显示了应用程序存储的 Cookie 数据。请注意,Cookie 的过期时间是一个小时,即 3600 秒,这是由 cookieMaxAge 属性配置的。如果你查看服务器日志,你会看到语言环境被记录下来了。

INFO : com.Olivia.spring.HomeController - Welcome home! The client locale is en.
INFO : com.Olivia.spring.HomeController - Welcome home! The client locale is fr.
INFO : com.Olivia.spring.HomeController - Welcome home! The client locale is fr.

这就是关于 Spring i18n 示例应用的全部内容,请从下方链接下载示例项目并进行操作,以便更多地了解。

下载 Spring i18n 项目

bannerAds