日期:2014-05-16  浏览次数:20293 次

简单 spring国际化 jsp显示
1:在MyEclipse下面创建一个test的Web Project,然后添加Spring相关的文件,在src根目录下创建applicationContext.xml文件。

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>


2:在src根目录下面创建4个资源文件:分别是

messages_zh.properties
main.title=你好

messages_en.properties
main.title=Hello World!

messages_ja.properties
main.title=こんにちは

messages_ko.properties
main.title=??????

3:在WebRoot根目录下面创建test.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>
WEB-INF/lib/spring.tld 可能要要改成"http://www.springframework.org/tags"
4:修改WEB-INF下面的web.xml

在web.xml加入
<!-- Define the basename for a resource bundle for I18N -->
<context-param>
    <param-name>
       javax.servlet.jsp.jstl.fmt.localizationContext
    </param-name>
    <param-value>ApplicationResources</param-value>
</context-param>
<context-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>
    classpath*:/applicationContext*,classpath*:META-INF/applicationContext*.xml
   </param-value>
</context-param>
<listener>
   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

这里需要注意的是
<context-param>
    <param-name>
       javax.servlet.jsp.jstl.fmt.localizationContext
    </param-name>
    <param-value>ApplicationResources</param-value>
</context-param>
如果使用jstl标签 <fmt:message key="main.title"/>
上面这个 localizationContext 要记得添加
如果使用spring自带的标签 <spring:message code="main.title" /> 则可省略

这样用Spring国际化的Test.jsp页面就做好了:),此种方法是自动默认当前用户的语言,比如客户端是日语系统,就自动寻找messages_ja.properties资源文件,是英语系统,就自动寻找messages_en.properties资源文件。