//res_en_US.properties
username=Username
password=Password
login=Login
//res_zh_CN.properties
username=\u7528\u6236\u540D
password=\u5BC6\u78BC
login=\u767B\u9304
//Demo1.java
package pers.demo;
import java.util.Locale;
import java.util.ResourceBundle;
import org.junit.Test;
/**
* 寫兩個配置文件,一個文件中存放中文信息,另一個存放英文信息
* 我們使用一個類,通過語言環境,最終識別加載哪一個類文件的信息: ResourceBundle
* 什麼語言環境: Locale
* - zh_CN
* - en_US
* new Locale("zh", "CN");
* Locale.getDefault();
* Locale.US
* @author jack870131
*
* 資源文件的名稱的格式: 基本名稱+Locale部分+.properties
* 例如: res_zh_CN.properties, 其中基本名稱為 res, 而 zh_CN 是 Locale 部分
* 必須所有的資源文件基石名稱要相同,不同之處就是 Locale
*/
public class Demo1 {
@Test
public void fun1() {
Locale locale = Locale.US;
//得到 ResourceLocale
//第一個參數是: 基本名稱
//第二個參數是: Locale
ResourceBundle rb = ResourceBundle.getBundle("res", locale);
//使用 ResourceBundle 來獲取資源信息
System.out.println(rb.getString("username"));
System.out.println(rb.getString("password"));
System.out.println(rb.getString("login"));
}
}
//login.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'login.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<%
/*
1. 獲取 Locale, 這是由客戶端的瀏覽器提供的 Locale
2. 創建 ResourceBundle
3. 把所有的語音信息使用 rb.getString("xxx") 來替換
*/
Locale locale = request.getLocale();
ResourceBundle rb = ResourceBundle.getBundle("res", locale);
%>
<h1><%=rb.getString("login") %></h1>
<form action="" method="post">
<%=rb.getString("username") %>: <input type="text" name="username"><br>
<%=rb.getString("password") %>: <input type="password" name="password"><br>
<input type="submit" value="<%=rb.getString("login") %>">
</form>
</body>
</html>