IBM®
跳转到主要内容
    中国 [选择]    使用条款
 
 
Select a scope: Search for:    
    首页    产品    服务与解决方案     支持与下载    个性化服务    
跳转到主要内容

developerWorks 中国  >  Web development  >

使用 Ajax 实现本地化后的客户端消息验证

developerWorks
文档选项

未显示需要 JavaScript 的文档选项

样例代码

英文原文

英文原文


级别: 中级

Ritesh Prasad, Senior Staff Software Engineer, IBM

2009 年 3 月 19 日

您在创建一个适合全球用户的 Web 应用程序时,有两点需要考虑:国际化/本地化了的页面内容及用户输入验证和消息显示。用资源包(特定于本地语言环境的属性文件)在服务器端构建一个页面的国际化版本很容易,但如果验证是在客户端进行的,那么显示国际化了的验证消息就非常困难了。Asynchronous JavaScript + XML (Ajax) 是可以简化此项工作的一个不错选择。本文将介绍如何联合使用 Ajax 与资源包来使国际化/本地化了的客户端验证消息处理的过程变得较为简单。

简介

在构建一个能影响全球用户的 Web 应用程序时,有两点需要考虑。第一点是需要呈现本地化后的页面内容,第二点是验证用户输入以及本地化后的验证消息显示。

使用资源包(特定于本地语言环境的属性文件)在服务器端构建此页面的本地化版本很容易。同样地,也可以使用服务器端验证来显示本地化后的验证消息。对于国际化而言,有很多具备良好支持的现成框架可用,比如 Jakarta Struts、Spring、Tapestry 和 Freemarker。不过,在几乎所有的这类框架内,都缺少对在客户端验证本地化消息的现成支持。

如果验证是在客户端进行的,将很难显示本地化后的验证消息。通过在构建页面时提前处理整个页面(包括静态内容和必要的 JavaScript 验证消息)或从特定于本地语言环境的资源包解析出消息键,可以显示这些消息。不过,上述方式具有一个暗含的限制:整个 JavaScript 验证逻辑都应在 JavaServer Page (JSP) 本身内编写以便基于 Java™ 的消息键解析逻辑可被重用。不要忘记,JavaScript 通常都是由页面设计人员编写的,而这些设计人员并不一定同时也掌握 Java 的开发技术。混合 Java 代码和 JavaScript 可能会让 Web 应用程序的开发和维护复杂化。

联合使用 Ajax 和资源包是另一种可以简化工作的方式。它让您能将此验证 JavaScript 移到另一个文件,而不是 JSP。并且,只对需要的消息键进行解析,而不是像使用预先构造的本地化版本方法一样,对所有消息键进行解析。

本文描述了如何联合使用 Ajax 和资源包来简化本地化后的客户端验证消息处理。我将侧重于使用 Ajax 的强大功能,而不会涉及现成框架的复杂性。本文所介绍的方式非常适合于需要快速响应的 Web 2.0 应用程序,比如动态跟踪用户动作。

在本文中,我不会过多涉及 JSP 页面内静态 HTML 内容的本地化。本文所侧重的是联合使用 Ajax 和资源包来实现本地化后的客户端验证消息处理。不过,用来在服务器端解析消息键的 Java 实用工具也可用于本地化 JSP 页面内的静态 HTML 内容。





回页首


关键字

国际化(Internationalization) — 指一种应用程序设计过程,使应用程序不需要进行重大修改就可适用于各种语言和地区。有时,国际化这一术语常被缩写为 i18n,因为在首字母 “i” 和最后一个字母 “n” 之间共有 18 个字母。

本地化(Localization) — 针对某个特定地区或语言调整软件的过程,添加特定于本地语言环境的组件和经过翻译的文本。本地化这一术语常被缩写为 l10n,这是因为在字母 “l” 和 “n” 之间共有 10 个字母。本地化的首要任务是翻译用户界面元素和文档。本地化所涉及的不仅是互换语言,而且还会涉及更改相关元素,比如数字、日期、货币等的显示。其他类型的数据(比如声音和图像)若对文化敏感,可能也都需要进行本地化。应用程序的国际化越好,越容易针对特定的语言和字符编码模式对其进行本地化。

Ajax 是一种技术,用来创建更好、更快且更为交互的 Web 应用程序。借助 Ajax,JavaScript 代码可使用 XMLHttpRequest 对象与服务器直接通信。有了此对象,JavaScript 代码可以在不重新装载页面的情况下与 Web 服务器进行数据交换。





回页首


开发一个国际化的 Web 应用程序

只要是针对全球(地理位置分散)用户开发 Web 应用程序,就要尊重和考虑用户对本地语言和文化的偏好。在 Web 应用程序内提供对国际化的支持时,需要考虑以下几点。

  • 识别出文化敏感数据
  • 在资源包中分离出可翻译文本
  • 处理混合消息
  • 格式化数字及货币
  • 格式化日期及时间
  • 使用 Unicode 字符属性
  • 正确地对比字符串
  • 将非 Unicode 文本转换为 Unicode




回页首


支持本地化了的客户端消息处理的高级步骤

在构建具有国际化支持和本地化了的客户端消息处理机制的 Web 应用程序时,下列几点是必须要满足的。

  • 所有本地化了的页面都应支持 UTF-8 字符集(页面编码)。
  • 所有客户端消息都应使用特定于客户机本地语言环境的资源包从服务器端获取。
  • 资源包应存储键值对。数值要使用 Unicode 字符。
  • 使用 Ajax 将来自客户端 JavaScript 的请求发送给一个服务器端资源,该资源会解析此请求以针对此键获得特定于客户机本地语言环境的消息。
  • 解析所获取的消息并正确显示。




回页首


使用 Ajax 实现本地化后的客户端消息处理的一种实用方式

在本节中,我们会带您亲历构建基本结构所需执行的各种操作,并会用一个示例页面对它进测试,然后会在您的 Web 应用程序中反复使用。

首先,要准备资源包属性文件。这些 *.properties 文件保存在该项目的类路径中,文件内包含键-值对,并可用作资源包来获得特定于本地语言环境的运行时解析的验证消息。所有这些 *.properties 文件都应符合 Java 国际化标准命名约定。


清单 1. 包属性文件
				
# org/rpd/i18n/bundles/Messages.properties - Resource Bundle for default locale
# The sample message key-value pairs...
error.loginid.required = User Name is Mandatory.
error.useremail.required = Email Id is Mandatory.
error.password.required = Password is required.
error.password.length = Password Length should not be less than six(6)character.
error.confirmpassword.required = Confirm Password is required.
error.passwordconfirm.match = Password and Confirm Password does not match.
error.firstName.required = First Name is required.
error.lastName.required = Last Name is required.          

接下来,创建一个 Java 类来管理这些资源包。这个类(比如说 ResourceManager.java)提供了将特定于本地语言环境的资源包加载到缓存的函数。借助它,还能根据给定消息键和本地语言环境检索消息值。


清单 2. ResourceManager.java
				
package org.rpd.i18n.common;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;

public class ResourceManager {
     // The name and location of the resource bundle.
     private final String mMessageBundle = "org/rpd/i18n/bundles/Messages";
     
     // The loaded message cache...
     private Map<Locale, ResourceBundle> mResourceCache = null;
     
     // Private instance variable.
     private static ResourceManager mManager = null;
     
     // default private constructor.
     private ResourceManager(){
          mResourceCache = new HashMap<Locale, ResourceBundle>();
     }
     
     
     // Get the locale-specific bundle from cache. 
// First load to the cache if not already loaded
     public ResourceBundle getBundle(Locale locale){
          if(locale == null){
               locale = Locale.getDefault();
          }
          if(mResourceCache.containsKey(locale) == false){
               ResourceBundle bundle = ResourceBundle.getBundle(mMessageBundle, locale);
               mResourceCache.put(locale, bundle);
          }
          return mResourceCache.get(locale);
     }

     // Thread safe Singleton pattern implementation... 
     private static ResourceManager getInstance(){
          synchronized (ResourceManager.class) {
               if(mManager == null){
                    mManager = new ResourceManager();
               }
          }
          return mManager;
     }
     
     // Get the message for the key using default locale.
     public static String getMessage(String key){
          return getMessage(key, null);
     }
     
     // Get the message for the key and specified locale.
     public static String getMessage(String key, Locale locale){
          try{
               return getInstance().getBundle(locale).getString(key);
          }catch(Exception e){
               return "";
          }
     }
}             

创建一个 JSP 文件来处理 Ajax 请求。这个 JSP 文件(例如,MessageResolver.jsp)负责处理 Ajax 请求以解析这些消息键(对这个 JSP 而言,就是请求参数,message-key)。它使用由 ResourceManager 类提供的消息检索特性来解析作为请求参数进入这个 JSP 的每个消息键。


清单 3. MessageResolver.jsp
				
<%@page import="org.rpd.i18n.common.ResourceManager"%>
<%
   // The name of the request parameter representing the input 
   // "HTML Element - Message Key" combination.
   final String REQ_ID = "message-key";
   // Message prefix to be used in output string.
   final String MSG_PREFIX = "begin::";
   // Message suffix to be used in output string.
   final String MSG_SUFFIX = "::end";
   // The standard "HTML Element - Message Key" delimiter.
   final String ELEMENT_KEY_DELIM = ",";
   // The "HTML Element - Localize Message" delimiter to be used in 
   // output string.
   final String KEY_VAL_DELIM = "==";
   
   // Find the request parameter containing the "HTML Element - Message Key" 
   // combination String.
   String keysArr = request.getParameter(REQ_ID);
   // If the desired request parameter doesn't exist, it means request is invalid.
   if(keysArr == null){
        out.println("Invalid message key");
   } else {
        // Split the input using the element - key delimiter (ELEMENT_KEY_DELIM).
        String keys[] = keysArr.split(ELEMENT_KEY_DELIM);
        // Check if the number of tuples is even. If not, it means the input is incorrect.
        if((keys.length%2) != 0){
      out.println("Improper elem-key combination: " + keysArr);
        } else {
      // Iterate through each elem-key combination. 
      for(int i=0; i < keys.length; i = i + 2){
           // Retrieve the localized message against the key. Prepare the result string 
           // as follows: 
           // Message Prefix (followed by) HTML Element key (followed by) Key-value 
           // delimiter 
           // (followed by) Localized value (followed by) Message suffix. 
           out.println(MSG_PREFIX + keys[i].trim() + KEY_VAL_DELIM + 
             ResourceManager.getMessage(keys[i+1].trim(), request.getLocale()) + 
             MSG_SUFFIX);
      }
        }
   }
%>     

准备 JavaScript 实用程序来管理 Ajax 调用。应该同时编写一组 JavaScript 例程(例如,MessageDisplay.js),这有助于为 MessageResolver.jsp 的 Ajax 调用创建正确的输入。JSP 需要的是一个请求参数,这个请求参数必须是一个由逗号分隔的字符串组。字符串由 HTML Element(占位符)Identifier 和消息键对组成,并且这个消息键将在解析之后显示在该 HTML 元素内。这里也会涉及到一个例程(displayMessage() 方法),用它来将解析后的消息正确地显示给相关的 HTML 元素。


清单 4. MessageDisplay.js
				
var xmlHttp = null;
var msgKeys = new Array();
var msgPrefix = "begin::";
var msgSuffix = "::end";
var msgDelimiter = "==";
var jspURL = "MessageResolver.jsp";

// reset msgKeys array.
function resetMsgKeys(){
     msgKeys = new Array();
}
// Adding to the array of keys
function addMsgKey(elemId, msgKey) {
     msgKeys[msgKeys.length] = new Array();
     msgKeys[msgKeys.length - 1][0] = elemId;
     msgKeys[msgKeys.length - 1][1] = msgKey;
     document.getElementById(elemId).innerText = "";
}

//Different browsers use different methods to create XMLHttpRequest objects.

function getXmlHttpObject() {
     xmlHttp = null;
     try {    
            // Firefox, Opera 8.0+, Safari    
   xmlHttp = new XMLHttpRequest();
     }
     catch (e) {    // Internet Explorer    
   try {
        xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
   }
   catch (e) {
        try {
      xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch (e) {
      alert("Your browser does not support Ajax!");
      return false;
        }
   }
     }
     return xmlHttp;
}


//To pass on the key to the JSP 
function getMessage(key) {
     // checking for browser support
     xmlHttp = getXmlHttpObject();
     if (xmlHttp == null) {
   alert("Browser does not support Ajax");
   return false;
     }
     var url = jspURL + "?message-key=" + key;
     xmlHttp.onreadystatechange = displayMessage;
     xmlHttp.open("GET", url, true);
     xmlHttp.send(null);
}


//Response generated against the request
function displayMessage() {
     if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
   var localizedMsg = xmlHttp.responseText;
   while (true) {
        var begInd = localizedMsg.indexOf(msgPrefix);
        var endInd = localizedMsg.indexOf(msgSuffix);
        if (begInd < 0 || endInd < 0) {
      break;
        }
        var msg = localizedMsg.substring((begInd + msgPrefix.length), endInd);
        var elemVal = msg.split(msgDelimiter);
        document.getElementById(elemVal[0]).innerText 
      = document.getElementById(elemVal[0]).innerText + "**" + elemVal[1];
        localizedMsg = localizedMsg.substring(endInd + msgSuffix.length);
   }
     }
}        

创建一个用于测试的客户机 JSP/HTML。这个页面(例如,NewUserRegistration.js)有一些输入字段,这些字段的数据需要用 JavaScript 在客户端进行验证。但是由于用户很有可能在输入数据时出错,因此,验证逻辑应能立即用恰当的消息提示用户。由于此验证消息应该被本地化,因而验证逻辑需要使用之前准备好的 Ajax 实用程序来针对各类有效性问题显示特定于本地语言环境的消息。


清单 5. NewUserRegistration.jsp
				
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
   <head>
      <title>New User Registration</title>
      <script type="text/javascript" src="ValidateNewUser.js"> </script>
      <script type="text/javascript" src="MessageDisplay.js"> </script>
   </head>
   <body>
      <form onsubmit="return validateNewUser();" name="frmRegistration" 
         id="frmRegistration" action="#" method="post">
         <table border="0" width="100%">
            <tbody>
               <tr>
                  <td align="right" nowrap="nowrap">&nbsp;Email ID</td>
                  <td align="center">:</td>
                  <td><input type="text" name="emailId" id="emailId" size="20"></td>
                  <td width="100%"><p id="emailErrMsg"></p></td>
               </tr>
               <tr>
                  <td align="right" nowrap="nowrap">User Name</td>
                  <td align="center">:</td>
                  <td><input type="text" name="loginId" id="loginId" size="20"></td>
                  <td width="100%"><p id="loginErrMsg"></p></td>
               </tr>
               <tr>
                  <td align="right" nowrap="nowrap">Password</td>
                  <td align="center">:</td>
                  <td><input type="password" name="password" id="password" 
                        size="20" ></td>
                  <td width="100%"><p id="passwordErrMsg"></p></td>
               </tr>
               <tr>
                  <td align="right" nowrap="nowrap">Confirm Password</td>
                  <td align="center">:</td>
                  <td><input type="password" name="confirmPassword" 
                       id="confirmPassword" size="20"></td>
                  <td width="100%"><p id="confirmpassErrMsg"></p></td>
               </tr>
               <tr>
                  <td align="right" nowrap="nowrap">First Name</td>
                  <td align="center">:</td>
                  <td><input type="text" name="firstName" id="firstName" size="20"></td>
                  <td width="100%"><p id="firstNameErrMsg"></p></td>
               </tr>
               <tr>
                  <td align="right" nowrap="nowrap">Last Name</td>
                  <td align="center">:</td>
                  <td><input type="text" name="lastName" id="lastName" size="20"></td>
                  <td width="100%"><p id="lastNameErrMsg"></p></td>
               </tr>
               <tr>
                  <td colspan="4" align="center">   
                     <input type="submit" name="cmdSubmit" value="Submit">
                  </td>
               </tr>
            </tbody>
         </table>
      </form>
   </body>
</html>      

在表单字段上应用验证条件。这个示例 JSP 具有一个表单,需要在此表单进行必要的输入以便完成用户的系统注册过程。此外,还需要满足一些验证条件才能对它进行提交:

/
  1. Email ID 和 User Name 字段是必需的。
  2. Password 字段也是必需的,且至少要有 6 个字符。
  3. Confirm Password 字段的值要与用户在 “Password” 字段所键入的值完全相同。
  4. First Name 与 Last Name 字段也是必需的。

创建 JavaScript 例程来验证表单。负责对各字段执行验证的 JavaScript 例程(例如,ValidateNewUser.js)要在 HTML 表单发生 onsubmit 事件时调用。它还会准备恰当的消息键和占位符 HTML Element ID 对,如需要,它们将被用作此 Ajax 调用内的输入以便解析和显示本地化了的消息。如果此表单通过了验证测试,它就会被提交给目标操作。


清单 6. ValidateNewUser.js
				
function validateNewUser() {
     resetMsgKeys();
     document.getElementById("loginErrMsg").innerText = "";
     document.getElementById("emailErrMsg").innerText = "";
     document.getElementById("passwordErrMsg").innerText = "";
     document.getElementById("confirmpassErrMsg").innerText = "";
     document.getElementById("firstNameErrMsg").innerText = "";
     document.getElementById("lastNameErrMsg").innerText = "";
               
     if (document.frmRegistration.loginId.value == "") {
          addMsgKey("loginErrMsg", "error.loginid.required");
     }
     if (document.frmRegistration.emailId.value == "") {
          addMsgKey("emailErrMsg", "error.useremail.required");
     
     if (document.frmRegistration.password.value == "") {
          addMsgKey("passwordErrMsg", "error.password.required");
     } else {
          if (document.frmRegistration.password.value.length < "6") {
               addMsgKey("passwordErrMsg", "error.password.length");
          }
     }
     if (document.frmRegistration.confirmPassword.value == "") {
          addMsgKey("confirmpassErrMsg", "error.confirmPassword.required");
     } else {
          if (document.frmRegistration.confirmPassword.value != 
               document.frmRegistration.password.value) {
               addMsgKey("confirmpassErrMsg", "error.passwordconfirm.match");
          }
     }
     if (document.frmRegistration.firstName.value == "") {
          addMsgKey("firstNameErrMsg", "error.firstName.required");
     }
     if (document.frmRegistration.lastName.value == "") {
          addMsgKey("lastNameErrMsg", "error.lastName.required");
     }
     if (msgKeys.length > 0) {
          getMessage(msgKeys);
          return false;
     }
     return true;
}                

部署与测试

将这个应用程序部署到任意一个 Web 服务器(例如,Tomcat)上,并启动此服务器实例。然后,打开一个浏览器实例(例如,Internet Explorer),找到客户机内设置的首选语言。它应该是 English,如图 1 所示(单击 这里 可以查看放大图)。


图 1. 语言首选
设置语言首选

浏览此 URL,寻找用户注册页面(NewUserRegistration.jsp),如图 2 所示(单击 这里 可以查看放大图)。


图 2. 用户注册
设置用户注册

在除 User Name 字段外的所有字段输入值。User Name 字段空着。按下 Submit。应该会看到如图 3 所示的 User Name 行旁边的验证消息(英语)(单击 这里 可以查看放大图)。


图 3. 输入用于验证的值
输入用于验证的值

更改浏览器(Internet Explorer)中的语言。删除 English 并加入 Hindi。


图 4. 将首选语言更改为 Hindi
将首选语言更改为 Hindi

关闭浏览器的这个实例并打开一个新实例。

再次浏览同一个(用户注册)页面。正确地输入所有字段,“User Name” 字段仍旧留空。应该会看到 “User Name” 行旁边显示的验证消息(印度语),如图 5 所示(单击 这里 可以查看放大图)。


图 5. 更新后的验证消息
更新后的验证消息




回页首


步骤总结

  1. 准备服务器端资源来解析消息键:
    1. 准备资源包(Messages*.properties)。定义一个 Java 实用程序(ResourceManager.java)来针对给定的键和本地语言环境解析特定于本地语言环境的消息值。
    2. 为 Ajax 调用定义一个服务器端请求处理程序 JSP(例如 MessageResolver.jsp)。
    3. 此 JSP 要有一个请求参数,例如,消息键。
    4. 这个消息键参数的值应是一个以逗号分隔的有效字符串列。
    5. 在用 “,” (逗号)作为分隔符分隔此值后,项的数目应该为偶数。
    6. 每个(连续)项对都应被分别处理。第一项应该是这个 HTML 元素的 ID,结果消息应在此 HTML 元素内显示。第二项应是要从此资源包解析出的实际的消息键。
    7. 按照预定义的结构准备此响应 — <Message Begin Delimiter> <HTML element ID> <Message-Key Delimiter> <Resolved internationalized message for the key> <Message End Delimiter>
    8. 为每个 HTML 元素和消息键重复同样格式。
  2. 在客户端验证的过程中:
    1. 准备占位符 HTML 元素 ID 和消息键对的列表。验证每个 HTML 表单字段并按前述要求准备此对。
    2. 从上面的 Element ID 和消息键对列表中创建一个以逗号分隔的字符串。
    3. 对此服务器端资源(即在步骤 1.a 中创建的 JSP)进行一次 Ajax 调用,追加一个查询字符串 “message-key=<Comma-separated list of Strings created in step 2.2>”。
  3. 在客户端,在处理来自 Ajax 调用的响应时:
    1. 解析这个由 JSP 生成的响应(步骤 1.f 到 1.g)。
    2. 分离 HTML 元素 ID 及相应的消息值的成对列表。
    3. 针对每个 HTML 元素进行合适的 JavaScript 调用以正确显示消息。




回页首


结束语

现在,您应该了解了用 Ajax 显示本地化后的客户端验证消息是多么简单。尽管我已经尽可能简化了设置,尽可能实现开箱即用,但本方式还是可以通过一些现成的系统和技术得到进一步改进。例如,如果您的 Web 应用程序使用 Jakarta Struts 或其他类似框架,而这些框架均能提供现成的、更完善的资源包的使用方法,那么您尽可以使用这些框架,而不是自己创建的 ResourceManager.java 实用程序类。类似地,JavaScript(和 Ajax)例程也可以编写得更为完善和全面,从而满足您自己的 Web 应用程序的标准和要求。






回页首


下载

描述名字大小下载方法
本文的示例应用程序LocalizationExample.zip14KBHTTP
关于下载方法的信息


参考资料



关于作者

Ritesh Prasad 的照片

Ritesh Prasad 是位于印度 Bangalore 的 Rational Application Developer 开发团队的一员。他具有 Indian Institute of Technology 的 Industrial Engineering and Management 专业的技术硕士学位并曾先后在几个 Web 应用程序开发项目中担任过 Java/J2EE 程序员。Ritesh 还从事过基于 J2EE 的 CRM Framework 方面的工作,比如 Chordiant 和 Eiphany,并有幸成为了 IBM India 接触 Epiphany 的第一人。在工作之外,Ritesh 喜欢与家人在一起和欣赏音乐。




对本文的评价










回页首


IBM 公司保留在 developerWorks 网站上发表的内容的著作权。未经IBM公司或原始作者的书面明确许可,请勿转载。如果您希望转载,请通过 提交转载请求表单 联系我们的编辑团队。
    关于 IBM 隐私条约 联系 IBM 使用条款