Spring MVC国际化(i18n)和本地化(L10n)示例

194 篇文章 3 订阅
46 篇文章 0 订阅

 

Spring MVC国际化(i18n)和本地化(L10n)示例

 

欢迎来到Spring Internationalization(i18n)教程。任何遍布全球的用户,国际化(i18n)或本地化(L10n)的Web应用程序对于更好的用户交互非常重要。

大多数Web应用程序框架提供了基于用户区域设置本地化应用程序的简单方法。Spring也遵循这种模式,通过为不同的语言环境使用Spring拦截器,Locale Resolvers和Resource Bundles,为国际化(i18n)提供广泛的支持。

一些早期关于java中的i18n的文章。

目录[ 隐藏 ]

春季国际化i18n

让我们创建一个简单的Spring MVC项目,我们将使用request参数来获取用户区域设置,并根据该区域设置特定于区域设置的资源包的响应页面标签值。

在Spring Tool Suite中创建一个Spring MVC项目,以获得我们应用程序的基本代码。如果您不熟悉Spring Tool Suite或Spring MVC Projects,请阅读Spring MVC示例

我们的本地化更改的最终项目如下图所示。我们将逐一研究应用程序的所有部分。

 

Spring i18n例如,弹簧i18n,弹簧定位,弹簧国际化,弹簧资源束

Spring i18n Maven配置

我们的Spring MVC pom.xml如下所示。


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://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 Resource Bundle

为简单起见,我们假设我们的应用程序仅支持两种语言环境--enfr。如果未指定用户区域设置,我们将使用英语作为默认区域设置。让我们为将在JSP页面中使用的这些语言环境创建spring资源包。

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="http://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国际化i18n - Bean配置文件

Spring Bean配置文件是所有魔法发生的地方。这是Spring框架的优点,因为它有助于我们更多地关注业务逻辑而不是编写琐碎的任务。让我们看一下我们的spring bean配置文件的外观,我们将逐一查看每个bean。

servlet-context.xml代码:


<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://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>
  1. 注释驱动标签启用了Controller编程模型,没有它Spring不会将HomeController识别为客户端请求的处理程序。
  2. context:component-scan提供了一个包,其中Spring将查找带注释的组件并将它们自动注册为Spring bean。
  3. messageSource bean配置为我们的应用程序启用i18n。basename属性用于提供资源包的位置。classpath:messages表示资源包位于类路径中,并遵循名称模式messages_{locale}.properties。defaultEncoding属性用于定义用于消息的编码。
  4. localeResolver bean类型org.springframework.web.servlet.i18n.CookieLocaleResolver用于在客户端请求中设置cookie,以便进一步的请求可以轻松识别用户区域设置。例如,我们可以要求用户在第一次启动Web应用程序时选择语言环境,并且使用cookie,我们可以识别用户区域设置并自动发送特定于语言环境的响应。我们还可以在客户端浏览器过期和删除之前指定cookie的默认语言环境,cookie名称和最大年龄。

    如果您的应用程序维护用户会话,那么您还可以使用org.springframework.web.servlet.i18n.SessionLocaleResolverlocaleResolver在用户会话中使用locale属性。配置类似于CookieLocaleResolver。

    
    <bean id="localeResolver"
    	class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
    	<property name="defaultLocale" value="en" />
    </bean>
    

    如果我们不注册任何“localeResolver”,默认情况下将使用AcceptHeaderLocaleResolver,它通过检查accept-language客户端HTTP请求中的标头来解析用户区域设置。

  5. org.springframework.web.servlet.i18n.LocaleChangeInterceptor拦截器配置为拦截用户请求并标识用户区域设置。参数名称是可配置的,我们使用locale的请求参数名称作为“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目录中。

以下是具有不同区域设置的应用程序主页的屏幕截图。

 

正如您在上图中所看到的那样,我们没有在客户端请求中传递区域设置信息,但我们的应用程序仍然识别用户区域设置。您现在必须猜到,这是因为我们在spring bean配置文件中配置了CookieLocaleResolver bean。但是,您可以检查浏览器cookie数据以进行确认。我正在使用chrome,下面的图像显示了应用程序存储的cookie数据。

请注意,cookie的到期时间是一小时,即由cookieMaxAge属性配置的3600秒。

如果要检查服务器日志,则可以看到该区域设置已被记录。


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.

这就是Spring i18n示例应用程序的全部内容,从下面的链接下载示例项目并使用它来了解更多信息。

下载Spring i18n项目

 

转载来源:https://www.journaldev.com/2610/spring-mvc-internationalization-i18n-and-localization-l10n-example

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
【2021年,将Spring全家桶的课程进行Review,确保不再有课程的顺序错乱,从而导致学员看不懂。进入2022年,将Spring的课程进行整理,整理为案例精讲的系列课程,并开始加入高阶Spring Security等内容,一步步手把手教你从零开始学会应用Spring,课件将逐步进行上传,敬请期待!】 本课程是Spring全家桶系列课程的第三部分Spring Boot,Spring案例精讲课程以真实场景、项目实战为导向,循序渐进,深入浅出的讲解Java网络编程,助力您在技术工作中更进一步。 本课程聚焦Spring Boot核心知识点:整合Web(如:JSP、Thymeleaf、freemarker等的整合)的开发、全局异常处理、配置文件的配置访问、多环境的配置文件设置、日志Logback及slf4j的使用、国际化设置及使用, 并在最后以一个贯穿前后台的Spring Boot整合Mybatis的案例为终奖,使大家快速掌握Spring的核心知识,快速上手,为面试、工作都做好充足的准备。 由于本课程聚焦于案例,即直接上手操作,对于Spring的原理等不会做过多介绍,希望了解原理等内容的需要通过其他视频或者书籍去了解,建议按照该案例课程一步步做下来,之后再去进一步回顾原理,这样能够促进大家对原理有更好的理解。 【通过Spring全家桶,我们保证你能收获到以下几点】 1、掌握Spring全家桶主要部分的开发、实现2、可以使用Spring MVCSpring Boot、Spring Cloud及Spring Data进行大部分的Spring开发3、初步了解使用微服务、了解使用Spring进行微服务的设计实现4、奠定扎实的Spring技术,具备了一定的独立开发的能力  【实力讲师】 毕业于清华大学软件学院软件工程专业,曾在Accenture、IBM等知名外企任管理及架构职位,近15年的JavaEE经验,近8年的Spring经验,一直致力于架构、设计、开发及管理工作,在电商、零售、制造业等有丰富的项目实施经验  【本课程适用人群】如果你是一定不要错过!  适合于有JavaEE基础的,如:JSP、JSTL、Java基础等的学习者没有基础的学习者跟着课程可以学习,但是需要补充相关基础知识后,才能很好的参与到相关的工作中。 【Spring全家桶课程共包含如下几门】 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值