IBM:使用AJAX構建應用程序

[color=indigo][b]----- library.js -----[/b][/color]
var req;
var url;

function startup() {
document.forms[0].subscriptionID.focus = true;
}

/* 創建XMLHttpRequest對象
* 處理Mozilla和非Microsoft瀏覽器
* try {
* req = new ActivexObject("Msxml2.XMLHTTP");
* } catch(e) {
* try {
* req = new ActiveObject("Microsoft.XMLHTTP");
* } catch(e) {
* req = false
* }
* }
* if(!req && typeof XMLHttpRequest != 'undefined') {
* req = new XMLHttpRequest();
* }
* 指定POST連接方法和要連接的URL,true表示請求一個異步連接
* Content-Type頭被設置爲讓服務器預知它能得到何種數據
* application/x-www-form-urlencoded讓服務器知道發送的是文本
*/
function init() {
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
var url = "/Library/LibraryServlet";
req.open("POST", url, true);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}

/* ①驗證訂購ID
* onreadystatechange告訴服務器運行完成後做什麼
* 如果服務器完成了請求,subscriptionValidator方法將被調用
* 獲取表單中用戶輸入的subscriptionID,以名/值對格式發送請求
* 請求被髮送到servlet,servlet處理請求並實時地發回響應
*/
function validate(formObj) {
init();
req.onreadystatechange = subscriptionValidator;
req.send("subscriptionID=" + formObj.subscriptionID.value);
}

/* ②查看作者和出版社
* field爲"author"或"pubs"
*/
function displayList(field) {
init();
titles.innerHTML = " ";
req.onreadystatechange = listHandler;
req.send("select=" + escape(field));
}

/* ③查看書名
* index獲取作者列表或出版社被選項的位置
* val獲取被選項的value值,如A1、P2
*/
function displayTitles(formObj) {
init();
var index = formObj.list.selectedIndex;
var val = formObj.list.options[index].value;
req.onreadystatechange = titlesHandler;
req.send("list=" + val);
}

/* ①響應被髮送回客戶機
* readystate等於4,客戶機接收到了響應而且接收完成
* status等於200,響應正常
* 調用responseXML屬性讀取響應
* 如果返回true,顯示"Subscription is valid",並且按鈕order被置爲不可用
*/
function subscriptionValidator() {
if (req.readystate == 4) {
if (req.status == 200) {
/* http://localhost:8080/Library/LibraryServlet?subscriptionID=john
* 返回信息:<message>true</message>
*/
var messageObj = req.responseXML.getElementsByTagName("message")[0];
var message = messageObj.childNodes[0].nodeValue;
if (message == "true") {
msg.innerHTML = "Subscription is valid";
document.forms[0].order.disabled = false;
} else {
msg.innerHTML = "Subscription not valid";
document.forms[0].order.disabled = true;
}
}
}
}

/* ③
*/
function titlesHandler() {
if (req.readystate == 4) {
if (req.status == 200) {
/* http://localhost:8080/Library/LibraryServlet?list=P1
* 返回信息:
* <root>
* <index>3</index>
* <list>Java Servlet Programming</list>
* <list>Enterprise JavaBeans</list>
* <list>Head First Java</list>
* </root>
*/
var titles = document.getElementById("titles");
var indexObj = req.responseXML.getElementsByTagName("index")[0];
var index = indexObj.childNodes[0].nodeValue;


var temp = "<select name=\"titles\" multiple>";

for (var i=0; i<index; i++) {
var listObj = req.responseXML.getElementsByTagName("list")[i];
temp = temp + "<option value=" + i +">" + listObj.childNodes[0].nodeValue + "</option>";
}

temp = temp + "</select>";
titles.innerHTML = temp;

}
}
}

/* ②
*/
function listHandler() {
var prefix;
if (req.readystate == 4) {
if (req.status == 200) {
/* http://localhost:8080/Library/LibraryServlet?select=author
* 返回信息:
* <root>
* <index>7</index>
* <list>---</list>
* <list>Jason Hunter</list>
* <list>Richard Monson - Haefel</list>
* <list>Kathy Sierra</list>
* <list>Michael Morrison</list>
* <list>Craig Larman</list>
* <list>Hanumant Deshmukh</list>
* </root>
*/
//var list = document.getElementById("list");
var authorOption = document.getElementById("select")
if (authorOption.checked) {
prefix = "A";
} else {
prefix = "P";
}
var list = document.getElementById("selectionList");
var indexObj = req.responseXML.getElementsByTagName("index")[0];
var index = indexObj.childNodes[0].nodeValue;
//選擇作者或出版社下拉框觸發onchange事件
var temp = "<select name=\"list\" onchange=\"displayTitles(this.form)\">";
for (var i=0; i<index; i++) {
var listObj = req.responseXML.getElementsByTagName("list")[i];
temp = temp + "<option value=" + prefix + i +">" + listObj.childNodes[0].nodeValue + "</option>";
}

temp = temp + "</select>";
list.innerHTML = temp;
}
}
}


[color=indigo][b]----- LibraryServlet.java -----[/b][/color]
package project.ajax; 

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.*;

/**
* @version 1.0
* @author
*/
public class LibraryServlet extends HttpServlet {

private Hashtable titles;
final private String ID = "John";

public void init() {
this.populateTitles();
}

/**
* @see javax.servlet.http.HttpServlet#void (javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.doPost(req, resp);
}

/**
* @see javax.servlet.http.HttpServlet#void (javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String option = null;
String key = null;
String[] list = null;
String xmlString = null;
String ID = null;

option = req.getParameter("select"); //②作者和出版社
key = req.getParameter("list"); //書名
ID = req.getParameter("subscriptionID"); //①訂購ID

//②
if (option != null) {
if (option.equals("author")) {
list = this.populateAuthors();
xmlString = this.getXMLData(list);
this.writeResponse(resp, xmlString);
} else if (option.equals("pubs")) {
list = this.populatePubs();
xmlString = this.getXMLData(list);
this.writeResponse(resp, xmlString);
}
}

//③
if (key != null ) {
list = this.getTitle(key);
xmlString = this.getXMLData(list);
this.writeResponse(resp, xmlString);
}

//①響應用XML格式發送,調用validID()方法獲取驗證信息
if (ID != null) {
String status = "<message>" + this.validID(ID) + "</message>";
this.writeResponse(resp, status);
}
}

//①設置響應的內容類型爲text/xml
//將頭Cache-Control的值設爲no-cache,這個值是必需的,AJAX要求響應的輸出不能被瀏覽器緩存
//調用getWriter().write()方法來寫響應
public void writeResponse(HttpServletResponse resp, String output) throws IOException {
resp.setContentType("text/xml");
resp.setHeader("Cache-Control", "no-cache");
resp.getWriter().write(output);
}

//③獲取Hashtable型titles的某個值
public String[] getTitle(String key) {
return (String[]) titles.get(key);

}

//②作者列表
private String[] populateAuthors() {
String[] authors = new String[7];
authors[0] = "---";
authors[1] = "Jason Hunter";
authors[2] = "Richard Monson - Haefel";
authors[3] = "Kathy Sierra";
authors[4] = "Michael Morrison";
authors[5] = "Craig Larman";
authors[6] = "Hanumant Deshmukh";

return authors;
}

//將字符串數組轉爲XML
private String getXMLData(String[] data) {
String xmlString = "";
xmlString = xmlString + "<root>";
xmlString = xmlString + "<index>" + data.length + "</index>";
for (int i=0; i<data.length; i++) {
xmlString = xmlString + "<list>" + data[i] + "</list>";
}
xmlString = xmlString + "</root>";

return xmlString;
}

//②出版社列表
private String[] populatePubs() {
String[] pubs = new String[5];
pubs[0] = "---";
pubs[1] = "Orielly";
pubs[2] = "Techmedia";
pubs[3] = "Pearson Education";
pubs[4] = "Manning";

return pubs;
}

private void populateTitles() {
titles = new Hashtable();
titles.put("A0", new String[] {"** blank **"});
titles.put("A1", new String[] {"Java Servlet Programming"});
titles.put("A2", new String[] {"Enterprise JavaBeans"});
titles.put("A3", new String[] {"Head First Java"});
titles.put("A4", new String[] {"XML Unleashed"});
titles.put("A5", new String[] {"Applying UML and Patterns"});
titles.put("A6", new String[] {"SCWCD Exam Study Kit"});

titles.put("P0", new String[] {" "});
titles.put("P1", new String[] {"Java Servlet Programming", "Enterprise JavaBeans", "Head First Java"});
titles.put("P2", new String[] {"XML Unleashed"});
titles.put("P3", new String[] {"Applying UML and Patterns"});
titles.put("P4", new String[] {"SCWCD Exam Study Kit"});
}

//①驗證ID,如果ID爲"John"返回true,否則返回false
private boolean validID(String ID) {
if (this.ID.equals(ID)) {
return true;
}

return false;

}
}


[color=indigo][b]----- order.jsp -----[/b][/color]
<html> 

<head>
<script type="text/javascript" src="/Library/library.js" >
</script>
</head>

<body onload="startup()">
<%@ page import="java.util.*" %>

<font face="Arial,Helvetica,Verdana" size="3">

<form name="LibraryForm" action="/Library/LibraryServlet">
<b>Enter Subscription ID: </b>
<input type="text" name="subscriptionID" onblur="validate(this.form)"/>    

<!-- Font for Status Message -->
<font face="Arial,Helvetica,Verdana" size="2" color="#FF0000">
<b id="msg"></b>
</font>
<!-- Font End -->
<hr>


<table height="300" width="600" border="1">
<tr>
<td valign="top" width="40%">

<!-- Font for Radio Buttons -->
<font face="Arial,Helvetica,Verdana" size="2">
<input type="radio" name="select" value="author" onclick="displayList('author')" /> 
<b>By Author</b>
<input type="radio" name="select" value="pubs" onclick="displayList('pubs')" />
<b>By Publisher</b>
</font>
<!-- Font End -->

<br><br>
<div id="selectionList">
</div>
</td>

<td width="20%"> </td>

<td valign="top" width="40%">
<b>Select Title: </b> <br>
<div id="titles"></div>
</td>

</tr>
</table>
<hr>
<input type="submit" name="order" value="Order" disabled />    
<input type="reset" name="cancel" value="Cancel" />
</form>

</font>

</body>
</html>


[color=indigo][b]----- web.xml -----[/b][/color]
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app id="WebApp">
<display-name>SoftwareLibrary</display-name>
<servlet>
<servlet-name>LibraryServlet</servlet-name>
<display-name>LibraryServlet</display-name>
<servlet-class>project.ajax.LibraryServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LibraryServlet</servlet-name>
<url-pattern>/LibraryServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<!--
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
-->
<welcome-file>order.jsp</welcome-file>
</welcome-file-list>
</web-app>


[color=red]轉載請註明[/color] 代碼來自:[url]https://www6.software.ibm.com/developerworks/cn/education/java/wa-ajax/index.html[/url]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章