java国际化demo解析

来源:互联网 发布:c语言刷题网站 编辑:程序博客网 时间:2024/04/26 04:06
国际化信息处理简单来说就是:
为每种语言提供一套相应的资源文件,并以规范化命名的方式保存在特定的目录中,由系统自动根据客户端语言选择适合的资源文件.
MessageFormat在NumberFormat和DateFormat的基础上提供了强大的占位符字符串的格式化功能,它支持时间、货币、数字以及对象属性的格式化操作。
1.配置spring文件(spring-mvc.xml)
像文件中加入以下配置:
bean的id一定是messageSource不是messageResource ,这是Spring规定的。
<!-- 定义国际化文件和编码 -->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:properties/base"/>
</bean>
此处class配置有两种,第一种是将资源文件放在源码里,bean为
<bean id="messageSource"
        class="org.springframework.context.support.ResourceBundleMessageSource">
第二种是文件配置在WEB-INF下面自己创建的目录下,bean为:
<bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">

<!-- Session判断用户语言,默认为中文 -->
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver" >
<!-- <property name="defaultLocale" value="cn"></property> -->
</bean>
<!-- 拦截器-->
<mvc:interceptors>
<bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang"/>
</bean>
</mvc:interceptors>
自定义的时候配置一下写法:
<!-- 数据库国际化资源 自定义的MessageResource -->
<bean id="messageSource" class="com.pactera.base.internationalization.MessageResource">
<property name="parentMessageSource" ref="propertiesMessageSource"/>
</bean>
2.添加多语言配置文件:
创建并将base_en_US.properties和base_zh_CN.properties添加到目录下,
国际化资源文件的命名规范规定资源名称采用以下的方式进行命名:
  <资源名>_<语言代码>_<国家/地区代码>.properties
其中,语言代码和国家/地区代码都是可选的。<资源名>.properties命名的国际化资源文件是默认的资源文件,即某个本地化类型在系统中找不到对应的资源文件,就采用这个默认的资源文件。
资源文件对文件内容有严格的要求:只能包含ASCII(美国信息交换标准代码)字符。所以必须将非ASCII字符的内容转换为Unicode代码的表示方式

以key-value的形式进行存储,并且key值不可以重复.有重复项会直接加载最后一个.

3.在controller中添加路径,例:
@Controllerpublic class HelloController { @RequestMapping("/hello.action") public String index() { return "hello"; }}
4.在jsp页面中使用
通过<spring:message code="welcome"/>将配置文件中的内容读取
加入标签:<%@taglib prefix="spring" uri="http://www.springframework.org/tags" %>
样例:
<%@ page language="java" contentType="text/html; charset=UTF-8"%><%@taglib prefix="spring" uri="http://www.springframework.org/tags" %><html><head> <title>SpringMVC<spring:message code="internationalisation"/></title></head><body> Language: <a href="?lang=zh_CN"><spring:message code="language.cn"/></a> &nbsp;&nbsp;&nbsp; <a href="?lang=en_US"><spring:message code="language.en"/></a> <h1> <spring:message code="welcome"/> </h1> 当前语言: ${pageContext.response.locale }</body></html>
访问该项目的/hello.action,通过链接可以切换语言
中文:
英文:
相关参考链接:
SpringMVC简单实现国际化/多语言
http://blog.csdn.net/u013360850/article/details/70860144
深入理解Java国际化
http://blog.csdn.net/zhoudaxia/article/details/37536195
spring 配置国际化资源文件的两种方式
http://blog.csdn.net/home_zhang/article/details/52489901