收藏 分销(赏)

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

上传人:pc****0 文档编号:8845619 上传时间:2025-03-04 格式:DOCX 页数:15 大小:197.01KB
下载 相关 举报
使用Ajax实现本地化后的客户端消息验证.docx_第1页
第1页 / 共15页
使用Ajax实现本地化后的客户端消息验证.docx_第2页
第2页 / 共15页
点击查看更多>>
资源描述
简介 在构建一个能影响全球用户的 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 mon; 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="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 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 具有一个表单,需要在此表单进行必要的输入以便完成用户的系统注册过程。此外,还需要满足一些验证条件才能对它进行提交: / a. Email ID 和 User Name 字段是必需的。 b. Password 字段也是必需的,且至少要有 6 个字符。 c. Confirm Password 字段的值要与用户在 “Password” 字段所键入的值完全相同。 d. 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;
展开阅读全文

开通  VIP会员、SVIP会员  优惠大
下载10份以上建议开通VIP会员
下载20份以上建议开通SVIP会员


开通VIP      成为共赢上传
相似文档                                   自信AI助手自信AI助手

当前位置:首页 > 包罗万象 > 大杂烩

移动网页_全站_页脚广告1

关于我们      便捷服务       自信AI       AI导航        抽奖活动

©2010-2025 宁波自信网络信息技术有限公司  版权所有

客服电话:4009-655-100  投诉/维权电话:18658249818

gongan.png浙公网安备33021202000488号   

icp.png浙ICP备2021020529号-1  |  浙B2-20240490  

关注我们 :微信公众号    抖音    微博    LOFTER 

客服