jsp页面
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Ajax Auto Complete</title>
<style type="text/css">
.mouseOut {
background: #708090;
color: #FFFAFA;
}
.mouseOver {
background: #FFFAFA;
color: #000000;
}
</style>
<script type="text/javascript">
var xmlHttp;
var completeDiv;
var inputField;
var nameTable;
var nameTableBody;
function createXMLHttpRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
}
function initVars() {
inputField = document.getElementById("names");
nameTable = document.getElementById("name_table");
completeDiv = document.getElementById("popup");
nameTableBody = document.getElementById("name_table_body");
}
function findNames() {
initVars();
if (inputField.value.length > 0) {
createXMLHttpRequest();
var url = "AutoCompleteServlet?names=" + inputField.value;
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = callback;
xmlHttp.send(null);
} else {
clearNames();
}
}
function callback() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
var name =xmlHttp.responseXML.getElementsByTagName("name")[0].firstChild.data;
setNames(xmlHttp.responseXML.getElementsByTagName("name"));
} else if (xmlHttp.status == 204){
clearNames();
}
}
}
function setNames(the_names) {
clearNames();
var size = the_names.length;
setOffsets();
var row, cell, txtNode;
for (var i = 0; i < size; i++) {
var nextNode = the_names[i].firstChild.data;
row = document.createElement("tr");
cell = document.createElement("td");
cell.onmouseout = function() {this.className='mouseOver';};
cell.onmouseover = function() {this.className='mouseOut';};
cell.setAttribute("bgcolor", "#FFFAFA");
cell.setAttribute("border", "0");
cell.onclick = function() { populateName(this); } ;
txtNode = document.createTextNode(nextNode);
cell.appendChild(txtNode);
row.appendChild(cell);
nameTableBody.appendChild(row);
}
}
function setOffsets() {
var end = inputField.offsetWidth;
var left = calculateOffsetLeft(inputField);
var top = calculateOffsetTop(inputField) + inputField.offsetHeight;
completeDiv.style.border = "black 1px solid";
completeDiv.style.left = left + "px";
completeDiv.style.top = top + "px";
nameTable.style.width = end + "px";
}
function calculateOffsetLeft(field) {
return calculateOffset(field, "offsetLeft");
}
function calculateOffsetTop(field) {
return calculateOffset(field, "offsetTop");
}
function calculateOffset(field, attr) {
var offset = 0;
while(field) {
offset += field[attr];
field = field.offsetParent;
}
return offset;
}
function populateName(cell) {
inputField.value = cell.firstChild.nodeValue;
clearNames();
}
function clearNames() {
var ind = nameTableBody.childNodes.length;
for (var i = ind - 1; i >= 0 ; i--) {
nameTableBody.removeChild(nameTableBody.childNodes[i]);
}
completeDiv.style.border = "none";
}
</script>
</head>
<body>
<h1>Ajax 自动完成实例</h1>
Names: <input type="text" size="20" id="names" οnkeypress="findNames()" style="height:20px;"/>
<div style="position:absolute;" id="popup">
<table id="name_table" bgcolor="#FFFAFA" border="0" cellspacing="0" cellpadding="0">
<tbody id="name_table_body"></tbody>
</table>
</div>
</body>
</html>
servlet 代码:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.cn.servlet;
import com.cn.service.NameService;
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.*;
import javax.servlet.http.*;
public class AutoCompleteServlet extends HttpServlet {
private List names = new ArrayList();
@Override
public void init(ServletConfig config) throws ServletException {
names.add("Abe");
names.add("Abel");
names.add("Abigail");
names.add("Abner");
names.add("Abraham");
names.add("Marcus");
names.add("Marcy");
names.add("Marge");
names.add("Marie");
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String prefix = request.getParameter("names");
NameService service = NameService.getInstance(names);
List matching = service.findNames(prefix);
if (matching.size() > 0) {
PrintWriter out = response.getWriter();
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
out.println("<response>");
Iterator iter = matching.iterator();
while (iter.hasNext()) {
String name = (String) iter.next();
out.println("<name>" + name + "</name>");
}
out.println("</response>");
matching = null;
service = null;
out.close();
} else {
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
java类:简单业务实现类,主要负责大小写转换,搜索以守字母开始的文本
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.cn.service;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class NameService {
private List names;
/** Creates a new instance of NameService */
private NameService(List list_of_names) {
this.names = list_of_names;
}
public static NameService getInstance(List list_of_names) {
return new NameService(list_of_names);
}
public List findNames(String prefix) {
String prefix_upper = prefix.toUpperCase();
List matches = new ArrayList();
Iterator iter = names.iterator();
while(iter.hasNext()) {
String name = (String) iter.next();
String name_upper_case = name.toUpperCase();
if(name_upper_case.startsWith(prefix_upper)){
boolean result = matches.add(name);
}
}
return matches;
}
}
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Ajax Auto Complete</title>
<style type="text/css">
.mouseOut {
background: #708090;
color: #FFFAFA;
}
.mouseOver {
background: #FFFAFA;
color: #000000;
}
</style>
<script type="text/javascript">
var xmlHttp;
var completeDiv;
var inputField;
var nameTable;
var nameTableBody;
function createXMLHttpRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
}
function initVars() {
inputField = document.getElementById("names");
nameTable = document.getElementById("name_table");
completeDiv = document.getElementById("popup");
nameTableBody = document.getElementById("name_table_body");
}
function findNames() {
initVars();
if (inputField.value.length > 0) {
createXMLHttpRequest();
var url = "AutoCompleteServlet?names=" + inputField.value;
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = callback;
xmlHttp.send(null);
} else {
clearNames();
}
}
function callback() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
var name =xmlHttp.responseXML.getElementsByTagName("name")[0].firstChild.data;
setNames(xmlHttp.responseXML.getElementsByTagName("name"));
} else if (xmlHttp.status == 204){
clearNames();
}
}
}
function setNames(the_names) {
clearNames();
var size = the_names.length;
setOffsets();
var row, cell, txtNode;
for (var i = 0; i < size; i++) {
var nextNode = the_names[i].firstChild.data;
row = document.createElement("tr");
cell = document.createElement("td");
cell.onmouseout = function() {this.className='mouseOver';};
cell.onmouseover = function() {this.className='mouseOut';};
cell.setAttribute("bgcolor", "#FFFAFA");
cell.setAttribute("border", "0");
cell.onclick = function() { populateName(this); } ;
txtNode = document.createTextNode(nextNode);
cell.appendChild(txtNode);
row.appendChild(cell);
nameTableBody.appendChild(row);
}
}
function setOffsets() {
var end = inputField.offsetWidth;
var left = calculateOffsetLeft(inputField);
var top = calculateOffsetTop(inputField) + inputField.offsetHeight;
completeDiv.style.border = "black 1px solid";
completeDiv.style.left = left + "px";
completeDiv.style.top = top + "px";
nameTable.style.width = end + "px";
}
function calculateOffsetLeft(field) {
return calculateOffset(field, "offsetLeft");
}
function calculateOffsetTop(field) {
return calculateOffset(field, "offsetTop");
}
function calculateOffset(field, attr) {
var offset = 0;
while(field) {
offset += field[attr];
field = field.offsetParent;
}
return offset;
}
function populateName(cell) {
inputField.value = cell.firstChild.nodeValue;
clearNames();
}
function clearNames() {
var ind = nameTableBody.childNodes.length;
for (var i = ind - 1; i >= 0 ; i--) {
nameTableBody.removeChild(nameTableBody.childNodes[i]);
}
completeDiv.style.border = "none";
}
</script>
</head>
<body>
<h1>Ajax 自动完成实例</h1>
Names: <input type="text" size="20" id="names" οnkeypress="findNames()" style="height:20px;"/>
<div style="position:absolute;" id="popup">
<table id="name_table" bgcolor="#FFFAFA" border="0" cellspacing="0" cellpadding="0">
<tbody id="name_table_body"></tbody>
</table>
</div>
</body>
</html>
servlet 代码:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.cn.servlet;
import com.cn.service.NameService;
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.*;
import javax.servlet.http.*;
public class AutoCompleteServlet extends HttpServlet {
private List names = new ArrayList();
@Override
public void init(ServletConfig config) throws ServletException {
names.add("Abe");
names.add("Abel");
names.add("Abigail");
names.add("Abner");
names.add("Abraham");
names.add("Marcus");
names.add("Marcy");
names.add("Marge");
names.add("Marie");
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String prefix = request.getParameter("names");
NameService service = NameService.getInstance(names);
List matching = service.findNames(prefix);
if (matching.size() > 0) {
PrintWriter out = response.getWriter();
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
out.println("<response>");
Iterator iter = matching.iterator();
while (iter.hasNext()) {
String name = (String) iter.next();
out.println("<name>" + name + "</name>");
}
out.println("</response>");
matching = null;
service = null;
out.close();
} else {
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
java类:简单业务实现类,主要负责大小写转换,搜索以守字母开始的文本
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.cn.service;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class NameService {
private List names;
/** Creates a new instance of NameService */
private NameService(List list_of_names) {
this.names = list_of_names;
}
public static NameService getInstance(List list_of_names) {
return new NameService(list_of_names);
}
public List findNames(String prefix) {
String prefix_upper = prefix.toUpperCase();
List matches = new ArrayList();
Iterator iter = names.iterator();
while(iter.hasNext()) {
String name = (String) iter.next();
String name_upper_case = name.toUpperCase();
if(name_upper_case.startsWith(prefix_upper)){
boolean result = matches.add(name);
}
}
return matches;
}
}