您的位置:首页 > 编程语言 > Java开发

Java SpringMVC实现国际化整合案例分析(i18n)

2017-12-27 15:31 447 查看
所谓国际化就是支持多种语言,web应用在不同的浏览环境中可以显示出不同的语言,比如说汉语、英语等。下面我将以具体的实例来举例说明:

(1)新建动态Java web项目,并导入几个SpringMVC必需的几个jar包,项目结构图和所需jar包如下:





(2)配置web.xml:

常规配置,没有什么特殊的地方,不多解释

(3)SpringMVC的配置文件springmvc-servlet.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> 
<context:component-scan base-package="springmvc国际化" />

<context:annotation-config />  <!-- 激活Bean中定义的注解 -->
<mvc:annotation-driven />

<!-- 视图相关配置 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/" />  <!-- 视图前缀 -->
<property name="suffix" value=".jsp" />  <!-- 视图后缀 -->
</bean>
<!-- 存储区域设置信息 -->
<!--基于Session的国际化实现:-->
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver" />
<!--  基于Cookie的国际化实现-->
<!--  <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" />-->
<!-- 国际化资源文件 -->
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">    
            <property name="basename" value="classpath:messages" />
</bean> <mvc:interceptors> <!-- 国际化操作拦截器 如果采用基于(请求/Session/Cookie)则必需配置 --> <bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"> <property name="paramName" value="lang" /> </bean> </mvc:interceptors></beans>


在上面的配置中,SessionLocaleResolver类通过一个预定义会话名将区域化信息存储在会话中。紧接着的“messageSource”配置的是国际化资源文件的路径,”classpath:messages”指的是classpath路径下的messages_zh_CN.properties文件和messages_en_US.properties文件。在这个配置文件的最后配置的是一个拦截器,该拦截器通过名为”lang”的参数来拦截HTTP请求,使其重新设置页面的区域化信息

(4)两个国际化资源文件:

i)messages_zh_CN.properties文件:

ii)messages_en_US.properties文件:

注:上面一些看起来“乱码”的地方实际上是经过Unicode编码的

(5)后台处理请求的controller:

这个controller很简单,就是转到一个视图页面welcome.jsp

(7)welcome.jsp:

可以看出,在需要使用国际化处理的地方都使用了Spring的message标签,code属性对应资源文件中的“键”名称

(8)最后的显示效果如下:

访问路径:http://localhost:8888/hello.html

i)中文:
http://localhost:8888/hello.html?lang=zh_CN
英文:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: