歡迎來到春季國際化(i18n)教程。任何面向世界各地用戶的 Web 應用程序,國際化(i18n)或本地化(L10n)對於改善用戶交互非常重要。大多數 Web 應用程序框架都提供了根據用戶語言環境設置輕鬆本地化應用程序的方法。Spring 也遵循這一模式,通過使用 Spring 拦截器、語言環境解析器和不同語言環境的資源包,為國際化(i18n)提供了廣泛的支持。一些早期關於 Java 的 i18n 文章:
Spring 國際化 i18n
讓我們創建一個簡單的Spring MVC項目,我們將使用請求參數來獲取用戶區域設置,並根據該設置從特定於區域的資源包中設置響應頁面標籤值。在Spring Tool Suite中創建一個Spring MVC項目,以獲得應用程序的基本代碼。如果您對Spring Tool Suite或Spring MVC項目不熟悉,請閱讀Spring MVC示例。我們的最終項目在區域更改後看起來如下圖。我們將逐一查看應用程序的所有部分。
Spring i18n 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.journaldev</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資源包,這將在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.journaldev.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 directive 配置Spring標籤庫。Spring會負責加載適當的資源包消息,並使其可供JSP頁面使用。
Spring國際化 i18n – Bean配置文件
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 Context: defines this servlet's request-processing
infrastructure -->
<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by @Controllers to .jsp resources
in the /WEB-INF/views directory -->
<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.journaldev.spring" />
</beans:beans>
-
annotation-driven 標籤啟用Controller編程模型,沒有它,Spring將不會將我們的HomeController認為是客戶端請求的處理程序。
-
context:component-scan 提供Spring將查找帶有標注組件並自動註冊為Spring bean的包。
-
messageSource bean 被配置為啟用應用程式的國際化。 basename 屬性用於提供資源包的位置。
classpath:messages
表示資源包位於類路徑中,並遵循名稱模式為messages_{locale}.properties
。defaultEncoding 屬性用於定義用於訊息的編碼。 -
localeResolver類型的
org.springframework.web.servlet.i18n.CookieLocaleResolver
bean 用於在客戶端請求中設置一個 cookie,以便後續請求可以輕鬆識別用戶的區域設置。例如,當用戶第一次啟動 Web 應用程序時,我們可以要求用戶選擇區域設置,並且通過使用 cookie,我們可以識別用戶的區域設置並自動發送區域特定的響應。我們還可以指定默認區域設置、cookie 名稱以及 cookie 過期前的最大有效期,在客戶端瀏覽器刪除。如果您的應用程序維護用戶會話,那麼您還可以使用org.springframework.web.servlet.i18n.SessionLocaleResolver
作為 localeResolver,以使用用戶會話中的 locale 屬性。配置與 CookieLocaleResolver 類似。<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"> <property name="defaultLocale" value="en" /> </bean>
如果我們沒有註冊任何“localeResolver”,則默認將使用AcceptHeaderLocaleResolver,該解析器通過檢查客戶端 HTTP 請求中的
accept-language
標頭來解析用戶的區域設置。 -
org.springframework.web.servlet.i18n.LocaleChangeInterceptor
攔截器被配置為攔截用戶請求並識別用戶的語言環境。參數名稱是可配置的,我們正在使用請求參數名稱“locale”作為語言環境。如果沒有此攔截器,我們將無法更改用戶的語言環境並根據用戶的新語言環境設置發送響應。它需要成為攔截器元素的一部分,否則 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 目錄下。這裡是我們應用程序主頁不同區域設置的截圖。默認首頁(en 區域): 將區域作為參數傳遞(fr 區域):
進一步的請求不帶區域:
如上圖所示,我們在客戶端請求中沒有傳遞區域信息,但我們的應用程序仍然識別出了用戶的區域。你現在一定已經猜到了,這是因為我們在 spring bean 配置文件中配置的 CookieLocaleResolver bean。但是你可以檢查你的瀏覽器 cookie 數據來確認它。我正在使用 Chrome,下面的圖像顯示了應用程序存儲的 cookie 數據。
請注意,cookie 的過期時間是一個小時,即 3600 秒,這是由 cookieMaxAge 屬性配置的。如果你查看服務器日誌,你可以看到區域信息被記錄了下來。
INFO : com.journaldev.spring.HomeController - Welcome home! The client locale is en.
INFO : com.journaldev.spring.HomeController - Welcome home! The client locale is fr.
INFO : com.journaldev.spring.HomeController - Welcome home! The client locale is fr.
那就是春季 i18n 示例应用的全部内容,从下面的链接下载示例项目,尽情玩耍以获取更多了解。