JavaWeb之国际化

 

时间:2016-12-13 19:17

 

 

为了满足不同语种的需求,对不同语言环境下进行访问所响应的页面中的文本采取变量形式进行响应。



1、编写配置文件

图片

2、使用类

import java.util.Locale;
import java.util.ResourceBundle;
 
import org.junit.Test;
/**
 * 先写两个配置文件
 *   一个文件中存放中文信息
 *   另一个文件存放英文信息
 * 使用一个类来通过语言环境进行识别所需要加载的文件信息
 *   ResourceBandle
 * 
 * 语言环境:Locale类
 *   >  zh_CN
 *   >  en_US
 *   new Locale("zh", "CN");
 *   Locale.getDefault();
 *   Locale.US
 * 
 * 资源文件的名称:基本名称+Locale部分+.properties
 *   例如:res_zh_CN.properties
 *   所有的资源文件的基本名称要相同
 * @author 31067
 *
 */
public class Demo1 {
    @Test
    public void fun1(){
        Locale locale = Locale.US;
        /*
         * 得到ResourceBundle
         * 第一个参数:基本名称
         * 第二个参数: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"));
    }
}



3、使用JSP

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
 
<%
    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">
 
</head>
 
    <%
        Locale locale = request.getLocale();
        ResourceBundle rb = ResourceBundle.getBundle("res", locale);
    %>
 
<body>
    <%--
        要想达到国际化的效果,需要把页面中所有与语言相关的字符串都写成变量
    --%>
    <h1><%=rb.getString("login") %></h1>
    <%=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") %>" />
</body>
</html>

 

posted @ 2017-02-07 17:59  WWWYC  阅读(154)  评论(0编辑  收藏  举报