IBM:AJAXによるアプリケーション構築


----- 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")[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;
  }
 }
}

----- 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[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[] {"&nbsp;"});
  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 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)"/> &nbsp; &nbsp; 

<!-- 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')" />&nbsp;
<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%">&nbsp;</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 /> &nbsp; &nbsp;
<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