為了實現國際化,我們在jsp中所用到的標簽等應該避免使用硬編碼,而應該使用資源文件中的key來代替,以動態的呈現不同的語言。運用jstl實現國際化有一下步驟:
- 編寫中英文資源文件 我們編寫兩個資源文件globalMessages_en_US.properties和globalMessages_zh_CN.properties
-
英文資源文件(globalMessages_en_US.propertie)內容:id=ID name=Your Name中文資源文件內容:id=用戶IDname=用戶名
- 為防止中文亂碼,將中文資源文件轉換成unicode編碼
-
id=\u7528\u6237ID name=\u7528\u6237\u540D
-
- jsp中利用jstl標簽引用資源文件,同時給該項目導入jstl.jar和standard.jar這兩個jar包,在jsp頁面中引入下面連個庫文件
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
....
<body> <!-- <fmt:setLocale value="${param.setLocale}"/> 區域語言的值從傳過來的參數中得到 --> <fmt:setLocale value="en_US"/> <!--指定區域語言--> <fmt:bundle basename="globalMessages"> <!-- 指定使用basename為globalMessages的資源文件,也即資源文件第一個單詞為globalMessages--> <center> <table> <tr> <td><fmt:message key="email"/></td> <td><input type="text" name="email"></td> </tr> </table> </center> </fmt:bundle> </body>