一.基于session的国际化实现:
首先配置我们项目的springservlet-mvc.xml文件添加的内容如下:
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<!-- 国际化信息所在的文件名 -->
<property name="basename" value="messages" />
<!-- 如果在国际化资源文件中找不到对应代码的信息,就用这个代码作为名称 -->
<property name="useCodeAsDefaultMessage" value="true" />
</bean>
<mvc:interceptors>
<!-- 国际化操作拦截器 如果采用基于(请求/Session/Cookie)则必需配置 -->
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
</mvc:interceptors>
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver" />
二、在项目中的源文件夹resources中添加messages.properties、messages_zh_CN.properties、messages_en_US.properties三个文件,其中messages.properties、messages_zh_CN.properties里面的"money", "date",为中文,messages_en_US.properties里面的为英文。 三、配置index.jsp
<%@ page contentType='text/html; charset=UTF-8'%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a href="switch?langType=zh">中文</a> | <a href="switch?langType=en">英文</a><br/>
<spring:message code="index"/>
</br>
哈哈哈哈 这是个主页
</body>
</html>
四、后台配置
/**
* 中英文语言切换
* 创建者 张志朋
* 创建时间 2016年8月1日
*
*/
@Controller
public class GlobalController extends BaseController {
@RequestMapping(value="/switch", method = {RequestMethod.GET})
public String test(HttpServletRequest request,Model model, @RequestParam(value="langType", defaultValue="zh") String langType){
if(langType.equals("zh")){
Locale locale = new Locale("zh", "CN");
request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,locale);
}
else if(langType.equals("en")){
Locale locale = new Locale("en", "US");
request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,locale);
}
else {
request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,LocaleContextHolder.getLocale());
}
return "modules/index";
}
}