在使用Google搜索或者是Baidu搜索的时候,在输入搜索关键字的同时,会自动弹出匹配的其他关键字的提示,全心全意为人民服务的精神在这里崭露无遗。这种利用Ajax技术实现输入提示和自动完成的功能是Google率先推出的,然后在其他的Web应用中被广泛的应用。利用Ajax实现部分页面刷新或者自动完成会使得用户体验绝大大提升。
技术永远是为用户服务的(无论是性能方面还是美观方面),脱离了用户就没有技术的发展,或者说只有用户才能促进技术的进步。
在掌握了Ajax原理之后我们也可以模仿谷歌,来实现一个搜索引擎的小Demo。
在实现的过程中主要运用的是Ajax技术,CSS+DIV布局,Servlet+JavaBean,还有数据库的基本知识等等。下面大致的描述一下实现的步骤,请大家跟随文字来共同完成我们的Google。有兴趣的朋友可以点击这里下载源码(实现仓促,如有不足之处请谅解)
1、准备后台以及数据库,完成数据库(MySql)操作部分。
这里很简单,首先编写ConnectionManager类,来实现对数据库的连接、查询功能。
代码如下:
- package com.ncs.common;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- public class ConnectionManager {
- private static String URL="jdbc:mysql://localhost:3306/test";
- private static String DRIVER="com.mysql.jdbc.Driver";
- private static String USER="root";
- private static String PASSWORD="123456";
- private static Connection conn=null;
- private static Statement stmt=null;
- private static ResultSet rs=null;
- public static void getConnection(){
- try {
- Class.forName(DRIVER);
- try {
- conn = DriverManager.getConnection(URL, USER, PASSWORD);
- System.out.println("Successfully connected to Mysql DB!");
- } catch (SQLException e) {
- System.out.println("Connection DB failed!");
- }
- } catch (ClassNotFoundException e) {
- System.out.println("Driver:"+DRIVER+" can't find!");
- }
- }
- public static void closeConnection(){
- try {
- conn.close();
- conn=null;
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- public static ResultSet executeQuery(String sql){
- try {
- stmt=conn.createStatement();
- rs=stmt.executeQuery(sql);
- return rs;
- } catch (SQLException e) {
- return null;
- }
- }
- public static void main(String[] args) {
- //getConnection();
- }
- }
package com.ncs.common;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ConnectionManager {
private static String URL="jdbc:mysql://localhost:3306/test";
private static String DRIVER="com.mysql.jdbc.Driver";
private static String USER="root";
private static String PASSWORD="123456";
private static Connection conn=null;
private static Statement stmt=null;
private static ResultSet rs=null;
public static void getConnection(){
try {
Class.forName(DRIVER);
try {
conn = DriverManager.getConnection(URL, USER, PASSWORD);
System.out.println("Successfully connected to Mysql DB!");
} catch (SQLException e) {
System.out.println("Connection DB failed!");
}
} catch (ClassNotFoundException e) {
System.out.println("Driver:"+DRIVER+" can't find!");
}
}
public static void closeConnection(){
try {
conn.close();
conn=null;
} catch (SQLException e) {
e.printStackTrace();
}
}
public static ResultSet executeQuery(String sql){
try {
stmt=conn.createStatement();
rs=stmt.executeQuery(sql);
return rs;
} catch (SQLException e) {
return null;
}
}
public static void main(String[] args) {
//getConnection();
}
}
2、编写页面
在页面中添加必须要有的文本框,以及两个按钮。其中必不可少的是在文本框输入文本时才出现的一个隐藏DIV。
代码如下:
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml" >
- <head>
- <title>Google</title>
- <%
- response.setHeader("Cache-Control","no-store");
- response.setHeader("Pragrma","no-cache");
- response.setDateHeader("Expires",0);
- %>
- <link type="text/css" href="css/autoComplete.css" rel="stylesheet"/>
- <script type="text/javascript" src="scripts/autoComplete.js"></script>
- </head>
- <body onload="setPosition($('txtKeyword'))">
- <div id="img"><img src="images/google.jpg"></img></div>
- <form id="form1">
- <div id="input"><input type="text" onkeydown="if(GetKeyCode(event)==13)form_submit()" onkeyup="GetSuggest(this.value,event);updown(event)" autocomplete="off" id="txtKeyword" />
- </div>
- <div id="dSuggest"></div>
- <div id="button">
- <input id="submit" type="submit" value="Google 搜索" onclick="alert('Now Search ...')" />
- <input id="submit" type="submit" value="手气不错" onclick="alert('Now Search ...')" />
- </div>
- </form>
- </body>
- </html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Google</title>
<%
response.setHeader("Cache-Control","no-store");
response.setHeader("Pragrma","no-cache");
response.setDateHeader("Expires",0);
%>
<link type="text/css" href="css/autoComplete.css" rel="stylesheet"/>
<script type="text/javascript" src="scripts/autoComplete.js"></script>
</head>
<body οnlοad="setPosition($('txtKeyword'))">
<div id="img"><img src="images/google.jpg"></img></div>
<form id="form1">
<div id="input"><input type="text" οnkeydοwn="if(GetKeyCode(event)==13)form_submit()" οnkeyup="GetSuggest(this.value,event);updown(event)" autocomplete="off" id="txtKeyword" />
</div>
<div id="dSuggest"></div>
<div id="button">
<input id="submit" type="submit" value="Google 搜索" οnclick="alert('Now Search ...')" />
<input id="submit" type="submit" value="手气不错" οnclick="alert('Now Search ...')" />
</div>
</form>
</body>
</html>
3、实现Servlet
编写Servlet来实现将页面的数据拼成Sql语句并传到ConnectionManager类,将返回的结果输出的页面。(需要注意的是,这里我们采用得是直接输出jsp代码,所以要为DIV加上id属性以便在CSS中控制样式,以及相关事件以便于在js中控制效果。)
代码如下:
- package com.ncs.servlet;
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import com.ncs.common.ConnectionManager;
- public class suggest extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
- req.setCharacterEncoding("UTF-8");
- // resp.setContentType("text/xml;charset=utf-8");
- System.out.println("Enter Servlet Get Method..");
- PrintWriter out=resp.getWriter();
- String param=(String)req.getParameter("id");
- String paramValue=param.trim().length()>0?param.trim():"unknown";
- String sql="select name from tbl_ajax_search where name like '"+paramValue+"%'";
- System.out.println("sql="+sql);
- ConnectionManager.getConnection();
- ResultSet rs=ConnectionManager.executeQuery(sql);
- StringBuffer sb=new StringBuffer();
- //sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
- // .append("<data>");
- sb.append("<ul id=\"sug\">");
- int pos=0;
- try {
- while(rs.next()){
- System.out.println("pos="+pos);
- sb.append("<li οnclick=\"form_submit()\" οnmοuseοver=\"myMouseOver(")
- .append(pos)
- .append(");\" onmouseOut=\"myMouseOut(")
- .append(pos)
- .append(");\">")
- .append(rs.getString(1)+"</li>");
- //sb.append("<item>")
- //.append(rs.getString(1))
- // .append("</item>");
- pos++;
- }
- sb.append("</ul>");
- int posi = sb.toString().indexOf("onmouseover");
- System.out.println("posi="+posi);
- if(posi==-1){
- System.out.println("no content found.");
- out.write("");
- }else{
- System.out.println(sb.toString());
- out.write(sb.toString());
- }
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
- // TODO Auto-generated method stub
- doGet(req,resp);
- }
- }
package com.ncs.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ncs.common.ConnectionManager;
public class suggest extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
// resp.setContentType("text/xml;charset=utf-8");
System.out.println("Enter Servlet Get Method..");
PrintWriter out=resp.getWriter();
String param=(String)req.getParameter("id");
String paramValue=param.trim().length()>0?param.trim():"unknown";
String sql="select name from tbl_ajax_search where name like '"+paramValue+"%'";
System.out.println("sql="+sql);
ConnectionManager.getConnection();
ResultSet rs=ConnectionManager.executeQuery(sql);
StringBuffer sb=new StringBuffer();
//sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
// .append("<data>");
sb.append("<ul id=\"sug\">");
int pos=0;
try {
while(rs.next()){
System.out.println("pos="+pos);
sb.append("<li οnclick=\"form_submit()\" οnmοuseοver=\"myMouseOver(")
.append(pos)
.append(");\" onmouseOut=\"myMouseOut(")
.append(pos)
.append(");\">")
.append(rs.getString(1)+"</li>");
//sb.append("<item>")
//.append(rs.getString(1))
// .append("</item>");
pos++;
}
sb.append("</ul>");
int posi = sb.toString().indexOf("onmouseover");
System.out.println("posi="+posi);
if(posi==-1){
System.out.println("no content found.");
out.write("");
}else{
System.out.println(sb.toString());
out.write(sb.toString());
}
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(req,resp);
}
}
4、仿照Google调整页面的布局
这里重点就是调整隐藏的DIV以及按钮的样式。
最终效果如下图
后记:关于模仿
自呱呱坠地我们就开始了自己一生的学习,在学习的过程中有着必不缺少的一个步骤:模仿。我们的学习大多是从模仿开始的,无论是模仿父母的声音牙牙学语,还是模仿大人走路的姿势蹒跚学步;无论是模仿书本上的文字一笔一画,还是模仿课文的结构字斟句酌。这都是开始学习的第一个过程——模仿。当然随着模仿的深入我们掌握了原理就可以开始下一个阶段的学习:使用和发挥。使用和发挥有赖于模仿的功力,只有初期模仿的到位,模仿的逼真,才能有后期的漂亮运用与灵活发挥。
我们的学习之路:模仿——使用——发挥