Auto complete example (1) 之ajax
sevelet代码如下,当然如果你也可以写一个jsp页面至于struts的action我倒美试过,如果大家知道告诉我一下哦
package com.sun.j2ee.blueprints.bpcatalog.ajax;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class AutocompleteServlet extends HttpServlet {
private ServletContext context;
private HashMap employees = new HashMap();
public void init(ServletConfig config) throws ServletException {
this.context = config.getServletContext();
employees.put("1", new EmployeeBean("1","Greg","Murray"));
employees.put("2", new EmployeeBean("2","Greg","Murphy"));
employees.put("3", new EmployeeBean("3","George","Murphy"));
employees.put("4", new EmployeeBean("4","George","Murray"));
employees.put("5", new EmployeeBean("5","Peter","Jones"));
employees.put("6", new EmployeeBean("6","Amber","Jones"));
employees.put("7", new EmployeeBean("7","Amy","Jones"));
employees.put("8", new EmployeeBean("8","Bee","Jones"));
employees.put("9", new EmployeeBean("9","Beth","Johnson"));
employees.put("10", new EmployeeBean("10","Cindy","Johnson"));
employees.put("11", new EmployeeBean("11","Cindy","Murphy"));
employees.put("12", new EmployeeBean("12","Duke","Hazerd"));
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
String action = request.getParameter("action");
String targetId = request.getParameter("id");
StringBuffer sb = new StringBuffer();
if (targetId != null) targetId = targetId.trim().toLowerCase();
boolean namesAdded = false;
if ("complete".equals(action)) {
Iterator it = employees.keySet().iterator();
while (it.hasNext()) {
String id = (String)it.next();
EmployeeBean e = (EmployeeBean)employees.get(id);
// simple matching only for start of first or last name
if ((e.getFirstName().toLowerCase().startsWith(targetId) ||
e.getLastName().toLowerCase().startsWith(targetId)) &&
!targetId.equals("")) {
sb.append("<employee>");
sb.append("<id>" + e.getId() + "</id>");
sb.append("<firstName>" + e.getFirstName() + "</firstName>");
sb.append("<lastName>" + e.getLastName() + "</lastName>");
sb.append("</employee>");
namesAdded = true;
}
}
if (namesAdded) {
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("<employees>" + sb.toString() + "</employees>");
} else {
//nothing to show
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
}
} if ("lookupbyname".equals(action)) {
Iterator it = employees.keySet().iterator();
ArrayList names = new ArrayList();
while (it.hasNext()) {
String id = (String)it.next();
EmployeeBean e = (EmployeeBean)employees.get(id);
// simple matching only for start of first or last name
if (e.getFirstName().toLowerCase().startsWith(targetId) ||
e.getLastName().toLowerCase().startsWith(targetId)) {
names.add(e);
}
}
if (names.size() > 0) {
request.setAttribute("employees", names);
}
context.getRequestDispatcher("/employees.jsp").forward(request, response);
} else if ("lookup".equals(action)) {
// put the target employee in the reqeust scope to display
if ((targetId != null) && employees.containsKey(targetId.trim())) {
request.setAttribute("employee", employees.get(targetId));
context.getRequestDispatcher("/employee.jsp").forward(request, response);
} else {
context.getRequestDispatcher("/error.jsp").forward(request, response);
}
}
}
}
下面jsp页面code如下:
<html>
<head>
<style type="text/css">
.popupItem {
background: #FFFAFA;
color: #000000;
text-decoration: none;
font-size: 1.2em;
}
.popupItem:hover {
background: #7A8AFF;
color: #FFFAFA;
}
.popupRow {
background: #FFFAFA;
}
</style>
<script type="text/javascript">
var isIE;
var completeTable;
var completeField;
var autorow;
var req;
function getElementY(element){
var targetTop = 0;
if (element.offsetParent) {
while (element.offsetParent) {
targetTop += element.offsetTop;
element = element.offsetParent;
}
} else if (element.y) {
targetTop += element.y;
}
return targetTop;
}
function init() {
completeField = document.getElementById("complete-field");
var menu = document.getElementById("auto-row");
autorow = document.getElementById("menu-popup");
autorow.style.top = getElementY(menu) + "px";
completeTable = document.getElementById("completeTable");
completeTable.setAttribute("bordercolor", "white");
}
function initRequest(url) {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
isIE = true;
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
function doCompletion() {
if (completeField.value == "") {
clearTable();
} else {
var url = "autocomplete?action=complete&id=" + escape(completeField.value);
var req = initRequest(url);
req.onreadystatechange = function() {
if (req.readyState == 4) {
if (req.status == 200) {
parseMessages(req.responseXML);
} else if (req.status == 204){
clearTable();
}
}
};
req.open("GET", url, true);
req.send(null);
}
}
function parseMessages(responseXML) {
clearTable();
var employees = responseXML.getElementsByTagName("employees")[0];
if (employees.childNodes.length > 0) {
completeTable.setAttribute("bordercolor", "black");
completeTable.setAttribute("border", "1");
} else {
clearTable();
}
for (loop = 0; loop < employees.childNodes.length; loop++) {
var employee = employees.childNodes[loop];
var firstName = employee.getElementsByTagName("firstName")[0];
var lastName = employee.getElementsByTagName("lastName")[0];
var employeeId = employee.getElementsByTagName("id")[0];
appendEmployee(firstName.childNodes[0].nodeValue,lastName.childNodes[0].nodeValue, employeeId.childNodes[0].nodeValue);
}
}
function clearTable() {
if (completeTable) {
completeTable.setAttribute("bordercolor", "white");
completeTable.setAttribute("border", "0");
completeTable.style.visible = false;
for (loop = completeTable.childNodes.length -1; loop >= 0 ; loop--) {
completeTable.removeChild(completeTable.childNodes[loop]);
}
}
}
function appendEmployee(firstName,lastName,employeeId) {
var firstNameCell;
var lastNameCell;
var row;
var nameCell;
if (isIE) {
row = completeTable.insertRow(completeTable.rows.length);
nameCell = row.insertCell(0);
} else {
row = document.createElement("tr");
nameCell = document.createElement("td");
row.appendChild(nameCell);
completeTable.appendChild(row);
}
row.className = "popupRow";
nameCell.setAttribute("bgcolor", "#FFFAFA");
var linkElement = document.createElement("a");
linkElement.className = "popupItem";
linkElement.setAttribute("href", "autocomplete?action=lookup&id=" + employeeId);
linkElement.appendChild(document.createTextNode(firstName + " " + lastName));
nameCell.appendChild(linkElement);
}
</script>
<title>Auto-Completion using Asynchronous JavaScript and XML (AJAX)</title>
</head>
<body οnlοad="init()">
<h1>Auto-Completion using Asynchronous JavaScript and XML (AJAX)</h1>
<hr/>
<p>
This example shows how you can do real time auto-completion using AJAX interactions.
</p>
<p>
In the form below enter a name. Possible names that will be completed are displayed below
the form. Click on one of the selections to see the employee details. Try typing "Greg", "Murray", "Jones", or ""Cindy".
</p>
<form name="autofillform" action="autocomplete" method="get">
<input type="hidden" name="action" value="lookupbyname"/>
<table border="0" cellpadding="5" cellspacing="0">
<tr>
<td><b>Employee Name:</b></td>
<td>
<input type="text"
size="20"
autocomplete="off"
id="complete-field"
name="id"
οnkeyup="doCompletion();">
</td>
<td align="left">
<input id="submit_btn" type="Submit" value="Lookup Employee">
</td>
</tr>
<tr><td id="auto-row" colspan="2"> <td/></tr>
</table>
</form>
<div style="position: absolute; top:170px;left:140px" id="menu-popup">
<table id="completeTable" border="1" bordercolor="black" cellpadding="0" cellspacing="0" />
</div>
</body>
</html>
web.xml文件配置如下:
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:j2ee="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
version="2.4"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<description>AutoCompletes Form Input using XmlHttpRequest Objects</description>
<servlet-name> AutocompleteServlet </servlet-name>
<servlet-class>com.sun.javaee.blueprints.bpcatalog.ajax.AutocompleteServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AutocompleteServlet</servlet-name>
<url-pattern>/autocomplete</url-pattern>
</servlet-mapping>
</web-app>
看看效果是否ok?