i18n組件中I18nTag類默認是經過request.getLocale().toString()來獲取瀏覽器語言,實現用戶自由切換語言需改動以下: javascript
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://www.openkoala.org/i18n" prefix="koala" %> <!DOCTYPE html> <html> <head> <title>I18N</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script src="/lib/jquery-1.8.3.min.js" type="text/javascript"></script> </head> <body> <select id="langSelect"> <option value="zh_CN">請選擇</option> <option value="zh_CN">中文</option> <option value="en_US">English</option> </select> I18N:<koala:i18n key="test" /> <script type="text/javascript"> $(function(){ $("#langSelect").change(function () { if (this.value) { $.post('${pageContext.request.contextPath}/international/switchLanguage.koala?locale=' + this.value).done(function(data){ if(data.result == 'success'){ window.location.reload(); }else{ alert("fail"); } }); } else { } }); }); </script> </body> </html>
建立I18NController類 html
package com.xiaokaceng.demo.web.controller; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/international") public class I18NController { @ResponseBody @RequestMapping("/switchLanguage") public Map<String, Object> switchLanguage(String locale, HttpSession session) { if (locale == null || locale.isEmpty()) { session.setAttribute("locale", "zh_CN"); } else { session.setAttribute("locale", locale); } Map<String, Object> result = new HashMap<String, Object>(); result.put("result", "success"); return result; } }
package com.xiaokaceng.demo.web.tag; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.jsp.JspException; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.tagext.SimpleTagSupport; import org.openkoala.framework.i18n.I18NManager; public class I18nTag extends SimpleTagSupport { private String key; private String locale; public void setKey(String key) { this.key = key; } public void setLocale(String locale) { this.locale = locale; } public void doTag() throws JspException, IOException { String message = null; HttpServletRequest request = (HttpServletRequest) ((PageContext) getJspContext()).getRequest(); try { if (this.locale == null) { this.locale = (String) request.getSession().getAttribute("locale"); } if (this.locale == null) { message = I18NManager.getMessage(this.key, request.getLocale().toString()); } else { message = I18NManager.getMessage(this.key, this.locale); } } catch (Exception e) { message = this.key; e.printStackTrace(); } getJspContext().getOut().write(message); } }配置i18n.tld元素<tag-class>com.xiaokaceng.demo.web.tag.I18nTag</tag-class>