---
title: "web项目国际化"
author: "g21121"
date: "2011-06-02T10:14:02Z"
tags: []
categories: ["企业架构"]
slug: "web"
draft: false
lastmod: "2016-05-24T16:55:29Z"
id: 1068128
url: "https://286.iteye.com/blog/1068128"
---

随着web项目的发展或多或少的会接触到国外的用户，这时就显示出了国际化得优势，国际化的好处就是在于项目一次性开发，不需后续代码的变更或少量变更就能做到支持更多语言，这给开发和维护带来了很多方便。

        国际化常用的方式有很多种，这里说一下比较常见的两种方式吧。

 

        一种是JSTL国际化：JSTL国际化在于不需要框架的支持，而且JSTL只要是Servlet2.0容器以上就支持，兼容性比较好。

        1.配置web.xml

```
<!-- jsp 标签库配置 -->
<jsp-config>
	<taglib>
		<taglib-uri>http://java.sun.com/jstl/core</taglib-uri>
		<taglib-location>/WEB-INF/tld/c.tld</taglib-location>
	</taglib>
	<taglib>
		<taglib-uri>http://java.sun.com/jsp/jstl/fmt</taglib-uri>
		<taglib-location>/WEB-INF/tld/fmt.tld</taglib-location>
	</taglib>
	<taglib>
		<taglib-uri>http://java.sun.com/jsp/jstl/functions</taglib-uri>
		<taglib-location>/WEB-INF/tld/fn.tld</taglib-location>
	</taglib>
</jsp-config>
```

        并且 拷贝tld标签到/WEB-INF/tld/下。

        2.jsp页面：

```
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>

　　JSTL 标签支持国际化的标签为

　　<fmt:bundle> <fmt:message> <fmt:setBundle><fmt:param>

　　<fmt:bundle> 功能：指定消息资源使用的文件

　　<fmt:message>功能：显示消息资源文件中指定key的消息,支持带参数消息

　　<fmt:param>

eg：
　<fmt:message key="$100312" bundle="${message}">

　　<fmt:param value="g21121"/>

　　</fmt:message>

　　<fmt:message key="$100313" bundle="${message}">

　　<fmt:param value="g21121"/>

　　</fmt:message> 
```

        bundle标签中的message是资源文件的名称，用户可以根据需要自己定义，定义成message\_zh\_CN,message\_en\_US均可。

        key标签中的值是资源文件中对应的键值。

        fmt:param对应的就是动态参数，例如： $100313=你好，{0}.

        页面输出的结果就是：你好，g21121.

        3.用户可以根据情况定义一个公共的jsp，来判断和绑定不同语言的资源文件。

```
<c:if test="${not empty param.lan}">
	<c:if test="${param.lan=='zh'}">
		<fmt:setLocale value="zh_CN" scope="session"/>        
	</c:if>        
	<c:if test="${param.lan=='en'}">          
		<fmt:setLocale value="en_US" scope="session"/>        
	</c:if>     
</c:if>
```

 

        另一种就是struts的国际化：这种国际化代码实现比较简单，与struts结合使用比较方便，并且更易于修改。

        1.首先配置web.xml

```
<!-- jsp 标签库配置 -->
<jsp-config>
	<taglib>
		<taglib-uri>/struts-tags</taglib-uri>
		<taglib-location>
			/WEB-INF/tld/struts-tags.tld
		</taglib-location>
	</taglib>
</jsp-config>
```

        导入struts.tld到/WEB-INF/tld/目录下。

        2.配置struts.properties

```
#资源文件名称，例如：messages_zh_CN，messages_en_US
struts.custom.i18n.resources=messages
#是否重新加载国际化
struts.i18n.reload=true
#默认本地国际化，设置了这个属性就意味着无论用户怎样改变浏览器语言，服务器输出的页面都会采用以下语言
struts.locale=zh_CN
#国际化语言编码
struts.i18n.encoding=UTF-8
```

        3.配置jsp页面

```
<%@taglib prefix="s" uri="/struts-tags"%>
<!-- name对应资源文件的键值 -->
<s:text name="$1021"/>
```

 

        是不是非常简单呢！

        验证是否成功，打开浏览器，选择“工具”--“Internet选项”--“语言”，添加和删除自己想测试的语言即可。