仿照 Goolge Suggest,主要用到的技术是ajax。定时的发送请求道数据库比对。
基本原理分析,当用户输入关键字,便向服务器发送请求,服务器根据用户输入的关键字,在数据库中搜索相关的关键字信息,并返回给客户端。
代码分析:java 根据输入关键字返回相应结果
package book.suggest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SearchSuggest extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
String search = request.getParameter("search");//获得请求中cate的值
System.out.println("哈哈 现在进的去了");
//定义查询数据库的SQL语句
String sql = "select title from suggest where title like '"+search+"%' order by title";
Connection conn = null;//声明Connection对象
Statement stmt = null;//声明Statement对象
ResultSet rs = null;//声明ResultSet对象
Vector vData = new Vector();
//response.setContentType("text/xml");//设置返回数据类型为xml格式
java.io.PrintWriter out = response.getWriter();
try {
// 加载数据库驱动类
Class.forName("com.mysql.jdbc.Driver");
// 访问数据库的地址
String url = "jdbc:mysql://localhost/treeview";
//创建Connection对象
conn = DriverManager.getConnection(url, "root", "12345678");
// 创建Statement对象
stmt = conn.createStatement();
// 执行SQL语句,返回记录集
rs = stmt.executeQuery(sql);
//定义AblumEO实体对象
while (rs.next())
{
vData.add(rs.getString("TITLE"));
}
StringBuffer buf = new StringBuffer();
for (int i=0;i<vData.size();i++)
{
String keyword = (String)vData.get(i);
buf.append(keyword+"\n");
}
out.print(buf.toString());
System.out.println(buf.toString());
// out.print(parasToXML(vData));//调用parasToXML()方法
} catch (Exception e) {
e.printStackTrace();
} finally {//最后关必记录集,Connection对象
try {
// this will close any associated ResultSets
if (stmt != null)
stmt.close();
if (conn != null)
conn.close();
} catch (SQLException sqle) {
}
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
doPost(request, response);
}
/*
public String parasToXML(Vector v) {// 该方法将数据转化成XML格式输出
StringBuffer buf = new StringBuffer();
buf.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
buf.append("<pictures>");
for (int i = 0; i < v.size(); i++) {
AlbumEO album = (AlbumEO) v.get(i);
buf.append("<item>");
buf.append("<name>" + album.getAlbumName() + "</name>");
buf.append("<url>" + album.getAlbumURL() + "</url>");
buf.append("<description>" + album.getAlbumDescription()
+ "</description>");
buf.append("</item>");
}
buf.append("</pictures>");
return buf.toString();
}
*/
}
ajax发送请求和处理返回信息
//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if(window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Your Browser Sucks!\nIt's about time to upgrade don't you think?");
}
}
function createAjaxObj(){
var httprequest=false
if (window.XMLHttpRequest)
{ // if Mozilla, Safari etc
httprequest=new XMLHttpRequest()
if (httprequest.overrideMimeType)
httprequest.overrideMimeType('text/xml')
}
else if (window.ActiveXObject)
{ // if IE
try {
httprequest=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e){
try{
httprequest=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){}
}
}
return httprequest
}
//Our XmlHttpRequest object to get the auto suggest
var searchReq = createAjaxObj();
//Called from keyup on the search textbox.
//Starts the AJAX request.
function searchSuggest() {
if (searchReq.readyState == 4 || searchReq.readyState == 0) {
var str = escape(document.getElementById('txtSearch').value);
searchReq.open("GET", 'search?search=' + str, true);
searchReq.onreadystatechange = handleSearchSuggest;
searchReq.send(null);
}
}
//Called when the AJAX response is returned.
function handleSearchSuggest() {
if (searchReq.readyState == 4) {
var ss = document.getElementById('search_suggest')
ss.innerHTML = '';
var str = searchReq.responseText.split("\n");
for(i=0; i < str.length - 1; i++) {
//Build our element string. This is cleaner using the DOM, but
//IE doesn't support dynamically added attributes.
var suggest = '<div onmouseover="javascript:suggestOver(this);" ';
suggest += 'onmouseout="javascript:suggestOut(this);" ';
suggest += 'onclick="javascript:setSearch(this.innerHTML);" ';
suggest += 'class="suggest_link">' + str[i] + '</div>';
ss.innerHTML += suggest;
}
}
}
//Mouse over function
function suggestOver(div_value) {
div_value.className = 'suggest_link_over';
}
//Mouse out function
function suggestOut(div_value) {
div_value.className = 'suggest_link';
}
//Click function
function setSearch(value) {
document.getElementById('txtSearch').value = value;
document.getElementById('search_suggest').innerHTML = '';
}
当输入框出发Onkeyup事件就发送请求
<html>
<head>
<style type="text/css" media="screen">
body {
font: 11px arial;
}
.suggest_link {
background-color: #FFFFFF;
padding: 2px 6px 2px 6px;
}
.suggest_link_over {
background-color: #E8F2FE;
padding: 2px 6px 2px 6px;
}
#search_suggest {
position: absolute;
background-color: #FFFFFF;
text-align: left;
border: 1px solid #000000;
}
</style>
<script language="JavaScript" type="text/javascript" src="ajax_search.js"></script>
</head>
<body>
<h3>Simple AJAX Search Suggest</h3>
<div style="width: 500px;">
<form id="frmSearch" action="">
<input type="text" id="txtSearch" name="txtSearch" alt="Search Criteria" onkeyup="searchSuggest();" autocomplete="off" />
<input type="submit" id="cmdSearch" name="cmdSearch" value="Search" alt="Run Search" /><br />
<div id="search_suggest">
</div>
</form>
</div>
</body>
</html>
xml配置文件:配置请求url
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>search</servlet-name>
<servlet-class>book.suggest.SearchSuggest</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>search</servlet-name>
<url-pattern>/search</url-pattern>
</servlet-mapping>
</web-app>