前言
为了满足各种国家,各种用户的需要,需要为不同用户展现不同语言的页面,这时候就需要用到国际化,springmvc对国际化提供了很好的支持,使用起来非常的方便。
实现
- springmvc.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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.test.controller" />
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- 国际化资源 -->
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<!-- 表示多语言配置文件在根路径下,以language开头的文件-->
<property name="basename" value="language"/>
<!-- 为true时: 当去取code的值时,如果没有取到,返回code; 为false时:如果没有取到,返回null; 默认该值为false -->
<property name="useCodeAsDefaultMessage" value="true"/>
</bean>
<!-- 基于Cookie实现的的配置 -->
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<!-- 存储在Cookie中的语言的名称 -->
<property name="cookieName" value="lang"></property>
<!-- 默认的语言 -->
<property name="defaultLocale" value="zh_CN"/>
<property name="cookiePath" value="/"/>
</bean>
<!-- 当发出修改语言的请求时,更新cookie中的语言 -->
<mvc:interceptors>
<bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<!-- url中语言参数的名称 -->
<property name="paramName" value="lang"/>
</bean>
</mvc:interceptors>
</beans>
-
语言配置文件
语言配置文件放在classpath下面
language_en_US.propertieswelcome = welcome
language_zh_CN.properties
welcome = 欢迎
-
jsp页面实现的方式,通过spring标签
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<html>
<head>
<title>SpringMVC</title>
</head>
<body>
<h2>Hello World!</h2>
语言:
<a href="?lang=zh_CN">中文</a>
<a href="?lang=en_US">英文</a>
<h1>
<spring:message code="welcome"/>
</h1>
</body>
</html>
- 后台实现方式
@Controller
public class I18nController {
@RequestMapping("/test")
@ResponseBody
public String test (HttpServletRequest request) {
RequestContext requestContext = new RequestContext(request);
return requestContext.getMessage("welcome");
}
}
补充
上面例子解决了后台国际化和页面国际化,但并不能满足全部情况,比如页面是通过js生成的情况,js的国际化实现,我目前的做法是一种语言建一个js文件,哈哈这个方法有点笨,如果你有什么好方法记得告诉我。
总结
springmvc实现国际化的思路是,当发送一个请求,从cookie中获取语言,通过语言(zh_CH),解析相应的语言文件,取里面的相应的code值 。切换语言时,拦截器会去修改cookie里的语言值实现切换。