在jsp頁面中使用國際化方法,首先將jstl開源架包:jstl.jar,standard.jar導進去
並在src目錄下建立以test開頭,.properties結尾的文件:test_en_US.properties,test_zh_CN.properties,文件內容分別為:
date=date,salary=salary /// date=\u65E5\u671F,salary=\u5DE5\u8D44
<%@page import="java.util.Locale"%> <%@page import="java.util.Date"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!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=UTF-8"> <title>Insert title here</title> </head> <body> <!-- 在jsp中設置,date和salary,並獲取 --> <% Date date=new Date(); request.setAttribute("date", date); double salary=321321.323; request.setAttribute("salary", salary); %> <br><br> date:<%=date %><br> salary:<%=salary %> <br><br> <!-- 利用jstl標簽庫,獲取開頭為test的.properties文件里的能容 , 其默認為中文的,即test_zh_CN.properties文件的值 message為//MessageFormet:可以格式化模塊字符串,formatDate和formetNumber... --> <fmt:bundle basename="test"> <fmt:message key="date"></fmt:message> <fmt:formatDate value="${date }"/> <fmt:message key="salary"></fmt:message> <fmt:formatNumber value="${salary }"></fmt:formatNumber> </fmt:bundle> <br><br> <!-- 動態獲取,顯示中英文切換 --> <% String code=request.getParameter("code"); if(code!=null){ if("en".equals(code)){ session.setAttribute("locale", Locale.US); } else if("zh".equals(code)){ session.setAttribute("locale", Locale.CHINA); } } %> <!-- 在session范圍內設置locale,便於在jsp中獲取locale --> <c:if test="${sessionScope.locale!=null }"> <fmt:setLocale value="${sessionScope.locale }"/> </c:if> <fmt:setBundle basename="test"/> <fmt:message key="date"></fmt:message> <fmt:formatDate value="${date }"/> <fmt:message key="salary"></fmt:message> <fmt:formatNumber value="${salary }"></fmt:formatNumber> <br><br> <a href="index.jsp?code=en">英文顯示</a> <br><br> <a href="index.jsp?code=zh">中文顯示</a> <br><br> </body> </html>
