CookieLocaleResolver不是默认的语言区域解析器,需要显式对其进行配置.使用他,SpringMVC会从Cookie中获取用户所设置的语言区域,来确定使用哪个语言区域.
示例:基于Cookie的国际化实现:
0.语言文件同Session,忽略.
1.修改配置文件
<!-- AcceptHeaderLocaleResolver配置 因为AcceptHeaderLocaleResolver是默认语言区域解析器,不配置也可以 --> <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" />
2.控制器
public class I18nController { @RequestMapping("/i18n") public String Form( String request_locale, HttpServletRequest request, HttpServletResponse response, Model model ) { if(request_locale != null) { if(request_locale.equals("zh_CN")) { Locale locale = new Locale("zh","CN"); (new CookieLocaleResolver()).setLocale(request,response,locale); } else if(request_locale.equals("en_US")) { Locale locale = new Locale("en","US"); (new CookieLocaleResolver()).setLocale(request,response,locale); } else { (new CookieLocaleResolver()).setLocale(request,response,LocaleContextHolder.getLocale()); } } return "i18n"; } }
3.视图
<!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>
4.Cookie影响语言文件的载入