使用Ajax实现本地化后的客户端消息验证_第1页
使用Ajax实现本地化后的客户端消息验证_第2页
使用Ajax实现本地化后的客户端消息验证_第3页
使用Ajax实现本地化后的客户端消息验证_第4页
使用Ajax实现本地化后的客户端消息验证_第5页
已阅读5页,还剩10页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、简介在构建一个能影响全球用户的 Web 应用程序时,有两点需要考虑。第一点是需要呈现本地化后的页面内容,第二点是验证用户输入以及本地化后的验证消息显示。使用资源包(特定于本地语言环境的属性文件)在服务器端构建此页面的本地化版本很容易。同样地,也可以使用服务器端验证来显示本地化后的验证消息。对于国际化而言,有很多具备良好支持的现成框架可用,比如 Jakarta Struts、Spring、Tapestry 和 Freemarker。不过,在几乎所有的这类框架内,都缺少对在客户端验证本地化消息的现成支持。如果验证是在客户端进行的,将很难显示本地化后的验证消息。通过在构建页面时提前处理整个页面(包括

2、静态内容和必要的 JavaScript 验证消息)或从特定于本地语言环境的资源包解析出消息键,可以显示这些消息。不过,上述方式具有一个暗含的限制:整个 JavaScript 验证逻辑都应在 JavaServer Page (JSP) 本身内编写以便基于 Java 的消息键解析逻辑可被重用。不要忘记,JavaScript 通常都是由页面设计人员编写的,而这些设计人员并不一定同时也掌握 Java 的开发技术。混合 Java 代码和 JavaScript 可能会让 Web 应用程序的开发和维护复杂化。联合使用 Ajax 和资源包是另一种可以简化工作的方式。它让您能将此验证 JavaScript 移到

3、另一个文件,而不是 JSP。并且,只对需要的消息键进行解析,而不是像使用预先构造的本地化版本方法一样,对所有消息键进行解析。本文描述了如何联合使用 Ajax 和资源包来简化本地化后的客户端验证消息处理。我将侧重于使用 Ajax 的强大功能,而不会涉及现成框架的复杂性。本文所介绍的方式非常适合于需要快速响应的 Web 2.0 应用程序,比如动态跟踪用户动作。在本文中,我不会过多涉及 JSP 页面内静态 HTML 内容的本地化。本文所侧重的是联合使用 Ajax 和资源包来实现本地化后的客户端验证消息处理。不过,用来在服务器端解析消息键的 Java 实用工具也可用于本地化 JSP 页面内的静态 HT

4、ML 内容。关键字国际化(Internationalization) 指一种应用程序设计过程,使应用程序不需要进行重大修改就可适用于各种语言和地区。有时,国际化这一术语常被缩写为 i18n,因为在首字母 “i” 和最后一个字母 “n” 之间共有 18 个字母。 本地化(Localization) 针对某个特定地区或语言调整软件的过程,添加特定于本地语言环境的组件和经过翻译的文本。本地化这一术语常被缩写为 l10n,这是因为在字母 “l” 和 “n” 之间共有 10 个字母。本地化的首要任务是翻译用户界面元素和文档。本地化所涉及的不仅是互换语言,而且还会涉及更改相关元素,比如数字、日期、货币等的

5、显示。其他类型的数据(比如声音和图像)若对文化敏感,可能也都需要进行本地化。应用程序的国际化越好,越容易针对特定的语言和字符编码模式对其进行本地化。Ajax 是一种技术,用来创建更好、更快且更为交互的 Web 应用程序。借助 Ajax,JavaScript 代码可使用 XMLHttpRequest 对象与服务器直接通信。有了此对象,JavaScript 代码可以在不重新装载页面的情况下与 Web 服务器进行数据交换。 开发一个国际化的 Web 应用程序 只要是针对全球(地理位置分散)用户开发 Web 应用程序,就要尊重和考虑用户对本地语言和文化的偏好。在 Web 应用程序内提供对国际化的支持时

6、,需要考虑以下几点。 · 识别出文化敏感数据 · 在资源包中分离出可翻译文本 · 处理混合消息 · 格式化数字及货币 · 格式化日期及时间 · 使用 Unicode 字符属性 · 正确地对比字符串 · 将非 Unicode 文本转换为 Unicode 支持本地化了的客户端消息处理的高级步骤 在构建具有国际化支持和本地化了的客户端消息处理机制的 Web 应用程序时,下列几点是必须要满足的。· 所有本地化了的页面都应支持 UTF-8 字符集(页面编码)。 · 所有客户端消息都应使用特定于客户机本地语

7、言环境的资源包从服务器端获取。 · 资源包应存储键值对。数值要使用 Unicode 字符。 · 使用 Ajax 将来自客户端 JavaScript 的请求发送给一个服务器端资源,该资源会解析此请求以针对此键获得特定于客户机本地语言环境的消息。 · 解析所获取的消息并正确显示。 使用 Ajax 实现本地化后的客户端消息处理的一种实用方式在本节中,我们会带您亲历构建基本结构所需执行的各种操作,并会用一个示例页面对它进测试,然后会在您的 Web 应用程序中反复使用。 首先,要准备资源包属性文件。这些 *.properties 文件保存在该项目的类路径中,文件内包含键-值

8、对,并可用作资源包来获得特定于本地语言环境的运行时解析的验证消息。所有这些 *.properties 文件都应符合 Java 国际化标准命名约定。 清单 1. 包属性文件 # org/rpd/i18n/bundles/Mperties - 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.e

9、rror.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

10、 is required.error.lastName.required = Last Name is required. 接下来,创建一个 Java 类来管理这些资源包。这个类(比如说 ResourceManager.java)提供了将特定于本地语言环境的资源包加载到缓存的函数。借助它,还能根据给定消息键和本地语言环境检索消息值。 清单 2. ResourceManager.javapackage mon;import java.util.HashMap;import java.util.Locale;import java.util.Map;import java.util.Resourc

11、eBundle;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 stati

12、c 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(loc

13、ale = 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 Res

14、ourceManager 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 speci

15、fied 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 类

16、提供的消息检索特性来解析作为请求参数进入这个 JSP 的每个消息键。 清单 3. MessageResolver.jsp <%page import="mon.ResourceManager"%><% / The name of the request parameter representing the input / "HTML Element - Message Key" combination. final String REQ_ID = "message-key" / Message prefix to b

17、e 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 - Lo

18、calize 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

19、9;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 i

20、s 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 P

21、refix (followed by) HTML Element key (followed by) Key-value / delimiter / (followed by) Localized value (followed by) Message suffix. out.println(MSG_PREFIX + keysi.trim() + KEY_VAL_DELIM + ResourceManager.getMessage(keysi+1.trim(), request.getLocale() + MSG_SUFFIX); %> 准备 JavaScript 实用程序来管理 Aja

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

23、ll;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 keysfunction addMsgKey(elemId, msgKe

24、y) msgKeysmsgKeys.length = new Array(); msgKeysmsgKeys.length - 10 = elemId; msgKeysmsgKeys.length - 11 = msgKey; document.getElementById(elemId).innerText = ""/Different browsers use different methods to create XMLHttpRequest objects.function getXmlHttpObject() xmlHttp = null; try / Firef

25、ox, 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;

26、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 = dis

27、playMessage; xmlHttp.open("GET", url, true); xmlHttp.send(null);/Response generated against the requestfunction displayMessage() if (xmlHttp.readyState = 4 | xmlHttp.readyState = "complete") var localizedMsg = xmlHttp.responseText; while (true) var begInd = localizedMsg.indexOf(m

28、sgPrefix); 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(elemVal0).innerText = document.getElementById(elemVal0).innerText +

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

30、UserRegistration.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> <scri

31、pt type="text/javascript" src="ValidateNewUser.js"> </script> <script type="text/javascript" src="MessageDisplay.js"> </script> </head> <body> <form onsubmit="return validateNewUser();" name="frmRegistration&q

32、uot; id="frmRegistration" action="#" method="post"> <table border="0" width="100%"> <tbody> <tr> <td align="right" nowrap="nowrap">&nbsp;Email ID</td> <td align="center">:</t

33、d> <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"

34、;>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>

35、; <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%&quo

36、t;><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&q

37、uot; 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&q

38、uot;>:</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" n

39、owrap="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"><

40、/p></td> </tr> <tr> <td colspan="4" align="center"> <input type="submit" name="cmdSubmit" value="Submit"> </td> </tr> </tbody> </table> </form> </body></html> 在表单字段上应用验证条件。这个示

41、例 JSP 具有一个表单,需要在此表单进行必要的输入以便完成用户的系统注册过程。此外,还需要满足一些验证条件才能对它进行提交: / a. Email ID 和 User Name 字段是必需的。 b. Password 字段也是必需的,且至少要有 6 个字符。 c. Confirm Password 字段的值要与用户在 “Password” 字段所键入的值完全相同。 d. First Name 与 Last Name 字段也是必需的。 创建 JavaScript 例程来验证表单。负责对各字段执行验证的 JavaScript 例程(例如,ValidateNewUser.js)要在 HTML 表单

42、发生 onsubmit 事件时调用。它还会准备恰当的消息键和占位符 HTML Element ID 对,如需要,它们将被用作此 Ajax 调用内的输入以便解析和显示本地化了的消息。如果此表单通过了验证测试,它就会被提交给目标操作。 清单 6. ValidateNewUser.js function validateNewUser() resetMsgKeys(); document.getElementById("loginErrMsg").innerText = "" document.getElementById("emailErrMsg&

43、quot;).innerText = "" document.getElementById("passwordErrMsg").innerText = "" document.getElementById("confirmpassErrMsg").innerText = "" document.getElementById("firstNameErrMsg").innerText = "" document.getElementById("las

44、tNameErrMsg").innerText = "" if (document.frmRegistration.loginId.value = "") addMsgKey("loginErrMsg", "error.loginid.required"); if (document.frmRegistration.emailId.value = "") addMsgKey("emailErrMsg", "error.useremail.required&

45、quot;); if (document.frmRegistration.password.value = "") addMsgKey("passwordErrMsg", "error.password.required"); else if (document.frmRegistration.password.value.length < "6") addMsgKey("passwordErrMsg", "error.password.length"); if (do

46、cument.frmRegistration.confirmPassword.value = "") addMsgKey("confirmpassErrMsg", "error.confirmPassword.required"); else if (document.frmRegistration.confirmPassword.value != document.frmRegistration.password.value) addMsgKey("confirmpassErrMsg", "error.

47、passwordconfirm.match"); if (document.frmRegistration.firstName.value = "") addMsgKey("firstNameErrMsg", "error.firstName.required"); if (document.frmRegistration.lastName.value = "") addMsgKey("lastNameErrMsg", "error.lastName.required&quo

48、t;); 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. 将

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论