SessionLocaleResolver不是默认的语言区域解析器,需要对其进行显式配置.如果使用他,SpringMVC会从HttpSession作用域中获取用户设置的语言区域,来确定使用哪个语言区域.
示例:基于HttpSession的国际化实现:
1.修改配置文件
<!-- messageSource国际化 --> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basenames" value="message" /> <property name="defaultEncoding" value="UTF-8" /> </bean> <!-- 国际化操作拦截器如果采用(Session或Cookie)则必须配置 --> <mvc:interceptors> <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" /> </mvc:interceptors> <!-- AcceptHeaderLocaleResolver配置 因为AcceptHeaderLocaleResolver是默认语言区域解析器,不配置也可以 --> <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver" />
2.建立语言文件
message_zh_CN.properties
title=我是标题
message_en_US.properties
title=IMTITLE
3.控制器
public class I18nController { @RequestMapping("/i18n") public String Form( String request_locale, HttpServletRequest request, Model model ) { if(request_locale != null) { if(request_locale.equals("zh_CN")) { Locale locale = new Locale("zh","CN"); request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, locale);; } else if(request_locale.equals("en_US")) { 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 "i18n"; } }
4.视图
<!DOCTYPE HTML> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" > <head> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %> <meta content="text/html;charset=UTF-8"/> <title>i18n</title> </head> <body> <h2><a href="/springTest/i18n?request_locale=zh_CN">中文</a>|<a href="/springTest/i18n?request_locale=en_US">英文</a></h2> <h2><spring:message code="title" /></h2> </body> </html>
中文:
英文: