|
----- library.js -----
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");
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");
temp = temp + "<option value=" + prefix + i +">" + listObj.childNodes[0].nodeValue + "</option>";
}
temp = temp + "</select>";
list.innerHTML = temp;
}
}
}
----- LibraryServlet.java -----
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 + "</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;
}
}
----- order.jsp -----
<html>
<head>
<script type="text/javascript" src="/Library/library.js" >
</script>
</head>
<body >
<%@ 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" />
<!-- 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" />
<b>By Author</b>
<input type="radio" name="select" value="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>
----- web.xml -----
<?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>
转载请注明 代码来自:https://www6.software.ibm.com/developerworks/cn/education/java/wa-ajax/index.html |
|
|