您的位置:首页 > 其它

基于Servlet百度搜索效果的Ajax的实现实例

2016-07-29 00:00 826 查看
在现在的web开发中,ajax技术经常会使用到,无刷新,响应快的特点也成为大家选择ajax的直接原因,本文通过一个简单的实例,提供类似百度搜索时候可以提供搜索结果选择的效果,来对ajax有着项目中的认识,当然,在此文中将使用最原始的ajax代码,不通过任何插件,通过基于servlet的方式来进行实现。

如果想了解ajax的原理以及相应的实现方式,可以参照一下博文的讲解

http://www.cnblogs.com/mingmingruyuedlut/archive/2011/10/18/2216553.html

首先给出本文项目中的具体实现图,如图1所示:



图1

本文所使用的代码,请通过以下链接下载

http://download.csdn.net/detail/songdeitao/6824119

首先给出项目的结构图,如图2所示:



图2

实现过程:

当通过链接http://localhost:8080/Ajax(具体的访问路径要参照自己部署的Tomcat以及配置)打开首页index.jsp时候,会出现和百度类似的输入框,如图3所示:



图3

此时index.jsp的具体内容如下:

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>Ajax小例子</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<script type="text/javascript" src="js/ajax.js"></script>
</head>
<body>
<form action="">
<input type="text" onkeyup="showAjax()" id="showAjaxText" style="width:300px;height:25px;background:scroll 0 0 #FFFFFF;"/>
<br/>
<div id="showAjaxId" style="width:300px;height:220px;display:none; overflow-y:auto;overflow-x:hidden;"> </div>
</form>
</body>
<script type="text/javascript">
//用来触发ajax的执行
function showAjax() {
// 获取文本框中输入的值
var content = document.getElementById("showAjaxText").value;
//调用ajax
doAjax("showAjaxId", "ajax.do?content=" + content);
//显示呈现的div
document.getElementById("showAjaxId").style.display = "block";
}
//将滚动条中选中的结果呈现在文本框中
function showClickText(obj) {
document.getElementById("showAjaxText").value = obj.innerHTML;
document.getElementById("showAjaxId").style.display = "none";
}
</script>
</html>


当输入字符a的时候,将会执行onkeyup="showAjax()"事件,然后调用showAjax()的javascript代码,执行doAjax("showAjaxId", "ajax.do?content=" + content);其中content就是输入的字符a,然后调用doAjax(……)方法,方法实现如下所示:

ajax.js

function doAjax(id, url) {
var xmlhttp = null;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}

else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

var index = url.indexOf("?");
if (index != -1) {
url += "&";
} else {
url += "?";
}
url += "time=" + new Date().getTime();
xmlhttp.open("post", url, true);
xmlhttp.send(null);

xmlhttp.onreadystatechange = function() {

if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var div = document.getElementById(id);
//alert(xmlhttp.responseText);
div.innerHTML = xmlhttp.responseText;
// div.innerHTML = div.innerHTML + xmlhttp.responseText;
}
}
}

执行ajax操作,这个时候就通过ajax执行servlet操作,下面给出web.xml的配置:

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>actionServlet</servlet-name>
<servlet-class>com.action.AjaxAction</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>actionServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>

根据配置,会执行com.action.AjaxAction类的操作,类AjaxAction.java如下所示:

AjaxAction.java

package com.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* 执行Ajax的action
*
* @author Steven
*
*/
public class AjaxAction extends HttpServlet {
private String[] str;
private static final long serialVersionUID = 1L;

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// 用来接收获取符合条件的结果
List<String> strList = new ArrayList<String>();
// StringBuffer sb = new StringBuffer();
// 获取前台输入的字符,去空格,转换成小写
String content = req.getParameter("content").trim().toLowerCase();
// 如果输入的字符存在且不为空
if (content != null && !"".equals(content)) {
// 将符合条件的结果放进集合中
for (String strTemp : str) {
// 以字符串开头
if (strTemp.toLowerCase().startsWith(content)) {
strList.add(strTemp);
// sb.append(strTemp);
// sb.append("<br/>");
}
}
}
// if (strList.size() > 10) {
// // 结果集只保存前十个元素
// strList = strList.subList(0, 10);
// }
// 存放到request属性范围中
req.setAttribute("strList", strList);
// 将结果在页面中输出
req.getRequestDispatcher("WEB-INF/jsp/showAjax.jsp").forward(req, resp);
// PrintWriter print = resp.getWriter();
// print.write(sb.toString());
}

@Override
public void init() throws ServletException {
// 初始化初始数据
// 相当于数据库
str = new String[] { "about", "above", "afraid", "after", "afternoon",
"again", "age", "ago", "agree", "air", "airplane", "airport",
"all", "almost", "along", "already", "also", "always",
"American", "and", "angry", "away", "autumn", "aunt", "August",
"ask", "as", "art", "arrive", "around", "arm", "April",
"apple", "appear", "apartment", "anything", "anyone", "any",
"answer", "another", "animal", "boy", "banana", "band",
"idiom", "illuminate", "highlight", "heritage", "grief",
"grab", "glitter", "legitimate", "likelihood", "media",
"mediate", "negligible", "narrative", "offence", "offensive",
"overthrow", "periodic", "publicity", "qualification",
"qualitative", "reign", "repay", "replacement", "revolve",
"scared", "seminar", "token", "transient", "update",
"vegetation", "virgin", "zinc", "yell", "yoke", "youngster",
"whereby", "ward", "vicious", "versatile", "tuck", "trigger",
"transient", "transaction", "theme", "handbook", "grim",
"extract", "entity", "edit", "distract", "discount",
"differentiate", "destiny", "delegate", "couch" };
}
}

在此类中,首先初始化了一些数据,也就是搜索时候匹配的数据,类似于数据库中的数据,当然在这里没有用到数据库,读者可以通过数据库关键字的查询得到结果,然后对结果进行操作。

接下来,看代码中通过req.getRequestDispatcher("WEB-INF/jsp/showAjax.jsp").forward(req, resp);跳转到showAjax.jsp界面,下面给出showAjax.jsp代码:

showAjax.jsp

<%@taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<table cellpadding="0" cellspacing="0" style="width:300px;color:black;font-size:12px;border:1px gray solid;">
<c:forEach items="${strList}" var="str">
<tr style="height:22px;" onmouseover="this.style.background='#BBB8B8';"
onmouseout="this.style.background='#FFFFFF'">
<td onmousedown="showClickText(this)">${str}</td>
</tr>
</c:forEach>
</table>

这个界面仅仅是对得到的结果进行以一个表格的形式显示。

最终结果如图4所示:



图4

注意:如果是Servlet项目,这个过程中会将showAjax.jsp中的内容显示就完成了,但此时却是显示index.jsp的页面,而且是将showAjax.jsp作为一个局部的页面显示在首页预留的<div id="showAjaxId" style="width:300px;height:220px;display:none; overflow-y:auto;overflow-x:hidden;"> </div>中,这就是通过ajax实现出来的效果。此时再来理解doAjax(div,action)方法的含义,就是触发action,通过servlet后台处理,将最终的结果显示到div中,当然div可以是其他的html标签容器,用来呈现ajax返回的结果。

返回的结果不仅可以是一个经过处理后的页面(最终也是一串html文本)也可以是字符串(可以是json方式),读者可以通过在本文的代码上进行修改实现效果。

本文所使用的代码,请通过以下链接下载

http://download.csdn.net/detail/songdeitao/6824119

在此恭祝大家学习愉快。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: