本节操作完成了springmvc下的国际化。
1、环境约束
- idea2018.1.5
- maven-3.0.5
- jdk-8u162-windows-x64
- spring 3.2.18
2、前提约束
3、在resources文件夹下创建两个资源文件
messages_en_US.properties【英文环境下所对应的键值对】,具体如下:
welcome =Welcome to wanho!
messages_zh_CN.properties【中文环境下所对应的键值对】,具体如下:
welcome=\u6b22\u8fce\u6765\u4e07\u548c\u0021
注意:资源文件中汉语对应显示的是unicode编码。
4、配置springmvc.xml
<!--国际化-->
<!-- 存储区域设置信息 -->
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver"/>
<!-- 国际化资源文件 -->
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages"/>
</bean>
<!--语言环境变化的拦截器-->
<mvc:interceptors>
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang"/>
</bean>
</mvc:interceptors>
<!--视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
5、在webapp/WEB-INF/jsp 下创建一个i18n.jsp
具体代码如下图所示:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%@taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<html>
<head>
</head>
<body>
<spring:message code="welcome"/>
</body>
</html>
6、创建net.wanho.controller.I18nController.java
package net.wanho.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class I18nController {
@RequestMapping("/i18n")
public String i18n()
{
return "i18n";
}
}
6、启动项目,测试
打开浏览器,输入http://localhost:8088/i18n,具体操作如下图所示:
测试国际化
至此,我们完成了springmvc的国家化,并完成了测试。