码迷,mamicode.com
首页 > 编程语言 > 详细

Spring国际化

时间:2014-11-15 21:27:30      阅读:291      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   ar   使用   sp   java   

   国际化(Internationalization)有时候被简称为i18n,因为有18个字母在国际化的英文单词的字母i和n之间。Spring对国际化的支持示例如下所示。

   需要将spring.tld放到工程的lib目录下,这样才能JSP才能正常使用spring:message标签。 

   web.xml中设置加启动时就要载配置文件applicationContext.xml

<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>
   classpath:applicationContext.xml
  </param-value>
 </context-param>
 <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>

   在applicationContext.xml中注册资源文件处理类。这里可以注册一个或者多个资源文件。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
 
   <bean id="messageSource"  class="org.springframework.context.support.ResourceBundleMessageSource">
 
      <property name="basename" value="messages"/>

   </bean>
 
   <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver"/>
   
</beans> 

  messageSource指明了资源文件的路径,这里的路径是根目录下的名为messages的资源文件件。

  CookieLocaleResolver是资源文件处理类,资源文件处理类有以下三种:

  1. 基于session的

  <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"/>

   2. 基于请求的

  <bean id="localeResolver" class="org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver"/>
   3.基于cookie的

  <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" />

  以上三种处理器理论上配置任意一个就可以,使用第一种和第三种比较常见。

     第一与第三个用法相同,只不过前者使用session,session过期就需要重新设置,而后者使用cookie,可以根据项目的具体情况进行选择。

 

    创建资源文件messages_zh.properties和messages_en.properties:    

messages_zh.properties内容如下: 
main.title=你好 

messages_en.properties内容如下:
main.title=Hello World! 

     

      JSP测试页面test.jsp如下:     

<%@ page language="java"  pageEncoding="UTF-8"%>
<%@ taglib prefix="spring" uri="WEB-INF/lib/spring.tld"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>Spring国际化</title>
  </head>
  <body> 
    <spring:message code="main.title" /><br>
    <input type="button" value=‘<spring:message code="main.title" />‘/><br>
  </body> 
</html>

 

    在Java代码中使用的例子如下:

//FileSystemXmlApplicationContext与ClassPathXmlApplicationContext的区别,前者需要写路径
  ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
    
  System.out.println(ctx.getMessage("main.title", null, Locale.getDefault()));

  System.out.println(ctx.getMessage("main.title", null, Locale.US));

 

Spring国际化

标签:style   blog   http   io   color   ar   使用   sp   java   

原文地址:http://www.cnblogs.com/lnlvinso/p/4100174.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!