这篇来利用Ajax做一个给搜索框添加搜索提示的功能,这个我们在百度首页,搜索框随便输入一个字符,就能弹出联想自动,可供用户选择,这篇要做的就是这么一个场景。

1.需求

java前端搜索功能实现的 javaweb搜索框如何实现搜索_java前端搜索功能实现的

就是这么一个功能。

 2.文件准备

需求中这个index.jsp中的搜索在我们原来项目中没有这个代码,所以这里先把这个素材拷贝进来。(具体素材在我这个项目github上有)

java前端搜索功能实现的 javaweb搜索框如何实现搜索_Javaweb_02

本篇主要是index.jsp和menu_search.jsp这两个文件。在index.jsp中静态包含了menu_search.jsp,代码中%@include file="menu_search.jsp" %,这行代码就是我们前面学习JSP指令学习过的静态包含,是在JSP转换Servlet时引入的文件。 

3.给搜索框添加信息提示框

在mene_search.jsp中,给搜索框先整出一个div框来,宽度和搜索框的宽度一样,为了显示明显,先来给边框添加红色。

在menu_serch.jsp文件底部,添加一个div,代码如下。

<div id="context1" style="border:1px solid red;background-color:white;width:126px;height:100px; position:absolute;left:860px;top:135px;">

  

</div>

浏览器刷新,看看效果。

java前端搜索功能实现的 javaweb搜索框如何实现搜索_AJAX搜索框联想提示实现_03

 

4.创建一个空的servlet文件

先创建一个SearchBookAJAXServlet.java,对应的url映射是/searchBookAJAXServlet

这部分代码后面来写。 

5.Dao层代码

在BookDao接口文件中,最底部添加这个代码

public List<Object> searchBookByName(String name) throws SQLException;

在BookDaoImpl.java添加对应的具体方法实现代码。

public List<Object> searchBookByName(String name) throws SQLException {
      QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
      return qr.query("select name from book where name like ?", new ColumnListHandler<Object>(), "%" +name+"%");
}

 

6. Service层代码

接着写BookService.java中代码,末尾新增以下代码。

public List<Object> searchBookByName(String name);

然后具体实现代码,在BookServiceImpl.java中末尾添加以下代码。

public List<Object> searchBookByName(String name) {
      try {
         return bd.searchBookByName(name);
      } catch (SQLException e) {
         e.printStackTrace();
      }
      return null;
   }

 

7.Servlet文件具体代码

下面是SearchBookAJAXServlet.java的完整代码。

package com.anthony.web.servlet;

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

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

import com.anthony.service.BookService;
import com.anthony.service.BookServiceImpl;


public class SearchBookAJAXServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		String name = request.getParameter("name");
		
		BookService bs = new BookServiceImpl();
		List<Object> list = bs.searchBookByName(name);
		// 把集合中元素转换成字符串返回到网页,多个元素逗号隔开
		String str = "";
		for (int i = 0; i < list.size(); i++) {
			if(i > 0) {
				str += ",";
			}
			str += list.get(i);
		}
		// 把数据响应到客户端
		response.getWriter().write(str);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

 

8.部署测试

部署到tomcat,重启tomcat服务。浏览器打开servlet地址,看看效果

http://localhost:8080/BookManagement/searchBookAJAXServlet?name=j

java前端搜索功能实现的 javaweb搜索框如何实现搜索_案例练习_04

这里我数据库看看是不是只有一个j开头的,这样我数据库book表再添加一个javascript看看。

java前端搜索功能实现的 javaweb搜索框如何实现搜索_Javaweb_05

这样就是说明代码没有问题了。

 

9. AJAX查询结果显示在div框中

下面我们来编辑menu_search.jsp文件,这里把文章开头写死div高度给删除,新加了AJAX这一套代码,代码修改如下

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<script type="text/javascript"
	src="${pageContext.request.contextPath}/js/my.js">
	
</script>
<script type="text/javascript">
	window.onload = function() {
		// 得到搜索框对象
		var searchElement = document.getElementById("name");
		searchElement.onkeyup = function() { // 给文本框注册按键弹起事件
			// 获取文本的值
			var name = this.value;
			// 获取xhr对象
			var xhr = getXMLHttpRequest();
			
			// 处理结果
			xhr.onreadystatechange = function(){
				if(xhr.readyState == 4){
					if(xhr.status == 200){//查看服务器响应状态
						var str = xhr.responseText; //得到服务器返回值
						// 得到div框元素
						var div = document.getElementById("context1");
						var ss = str.split(",");
						var childDivs = "";
						for (var i = 0; i < ss.length; i++) {
							childDivs += "<div>" + ss[i]+ "</div>";
						}
						div.innerHTML = childDivs;
					}
				}
			}
			
			xhr.open("get", "${pageContext.request.contextPath}/searchBookAJAXServlet?name=" + name +"&time=" + new Date().getTime());
			xhr.send(null);
		}
		
	}
</script>

<div id="divmenu">
	<a
		href="${pageContext.request.contextPath}/showProductByPage?category=文学">文学</a>
	<a
		href="${pageContext.request.contextPath}/showProductByPage?category=生活">生活</a>
	<a
		href="${pageContext.request.contextPath}/showProductByPage?category=计算机">计算机</a>
	<a
		href="${pageContext.request.contextPath}/showProductByPage?category=外语">外语</a>
	<a
		href="${pageContext.request.contextPath}/showProductByPage?category=经营">经管</a>
	<a
		href="${pageContext.request.contextPath}/showProductByPage?category=励志">励志</a>
	<a
		href="${pageContext.request.contextPath}/showProductByPage?category=社科">社科</a>
	<a
		href="${pageContext.request.contextPath}/showProductByPage?category=学术">学术</a>
	<a
		href="${pageContext.request.contextPath}/showProductByPage?category=少儿">少儿</a>
	<a
		href="${pageContext.request.contextPath}/showProductByPage?category=艺术">艺术</a>
	<a
		href="${pageContext.request.contextPath}/showProductByPage?category=原版">原版</a>
	<a
		href="${pageContext.request.contextPath}/showProductByPage?category=科技">科技</a>
	<a
		href="${pageContext.request.contextPath}/showProductByPage?category=考试">考试</a>
	<a
		href="${pageContext.request.contextPath}/showProductByPage?category=生活百科">生活百科</a>
	<a href="${pageContext.request.contextPath}/showProductByPage"
		style="color:#FFFF00">全部商品目录</a>
</div>
<div id="divsearch">
	<form action="${pageContext.request.contextPath}/findProductBySearch"
		method="post">
		<table width="100%" border="0" cellspacing="0">
			<tr>
				<td style="text-align:right; padding-right:220px">
				Search <input
					type="text" name="name" class="inputtable" onkeyup="searchName();"
					id="name" /> 
					<input type="image" src="images/serchbutton.gif"
					border="0" style="margin-bottom:-4px">
				</td>
			</tr>
		</table>

	</form>
</div>
<div id="context1" style="border:1px solid red;background-color:white;width:126px; position:absolute;left:860px;top:135px;">
	
</div>

刷新浏览器,看看/index.jsp效果,搜索框输入一个J看看,div框提示的效果。

java前端搜索功能实现的 javaweb搜索框如何实现搜索_AJAX搜索框联想提示实现_06

到这里,还有问题没有解决,那就是点击div中提示,不能点击,我们需要点击之后,自动填充到search框。

10. Div中name鼠标悬停变颜色

就是在div提示的name,鼠标悬停,会自动变颜色,例如变成灰色,离开name区域变成原来的白色,来看看这个怎么实现

<script type="text/javascript">
	window.onload = function() {
		// 得到搜索框对象
		var searchElement = document.getElementById("name");
		searchElement.onkeyup = function() { // 给文本框注册按键弹起事件
			// 获取文本的值
			var name = this.value;
			// 获取xhr对象
			var xhr = getXMLHttpRequest();
			
			// 处理结果
			xhr.onreadystatechange = function(){
				if(xhr.readyState == 4){
					if(xhr.status == 200){//查看服务器响应状态
						var str = xhr.responseText; //得到服务器返回值
						// 得到div框元素
						var div = document.getElementById("context1");
						var ss = str.split(",");
						var childDivs = "";
						for (var i = 0; i < ss.length; i++) {
							childDivs += "<div onmouseover='changeBackground_over(this)' onmouseout='changeBackground_out(this)'>" + ss[i]+ "</div>";
						}
						div.innerHTML = childDivs;
					}
				}
			}
			
			xhr.open("get", "${pageContext.request.contextPath}/searchBookAJAXServlet?name=" + name +"&time=" + new Date().getTime());
			xhr.send(null);
		}
		
	}
	
	function changeBackground_over(div) {
		div.style.backgroundColor = "grey";
	}
	
	function changeBackground_out(div) {
		div.style.backgroundColor = "white";
	}
</script>

上面改动地方在changeBackground_over(div) 和changeBackground_out(div)

刷新浏览器,看看效果。

java前端搜索功能实现的 javaweb搜索框如何实现搜索_java前端搜索功能实现的_07

鼠标悬停变成灰色,鼠标离开变成白色,对比看看上面改动的两个这个动作的function就明白了。

 

11.解决点击搜索按钮,填充到搜索框

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<script type="text/javascript"
	src="${pageContext.request.contextPath}/js/my.js">
	
</script>
<script type="text/javascript">
	window.onload = function() {
		// 得到搜索框对象
		var searchElement = document.getElementById("name");
		// 得到div框元素
		var div = document.getElementById("context1");
		searchElement.onkeyup = function() { // 给文本框注册按键弹起事件
			// 获取文本的值
			var name = this.value;
			if(name == ""){
				div.style.display="none";
				return;
			}
			// 获取xhr对象
			var xhr = getXMLHttpRequest();
			
			// 处理结果
			xhr.onreadystatechange = function(){
				if(xhr.readyState == 4){
					if(xhr.status == 200){//查看服务器响应状态
						var str = xhr.responseText; //得到服务器返回值
						var ss = str.split(",");
						var childDivs = "";
						for (var i = 0; i < ss.length; i++) {
							childDivs += "<div onclick='writeText(this)' onmouseover='changeBackground_over(this)' onmouseout='changeBackground_out(this)'>" + ss[i]+ "</div>";
						}
						div.innerHTML = childDivs;
						div.style.display="block";//把列表隐藏
					}
				}
			}
			
			xhr.open("get", "${pageContext.request.contextPath}/searchBookAJAXServlet?name=" + name +"&time=" + new Date().getTime());
			xhr.send(null);
		}
		
	}
	
	//鼠标悬浮时,改变背景色
	function changeBackground_over(div) {
		div.style.backgroundColor = "grey";
	}
	
	//鼠标离开时,恢复背景色
	function changeBackground_out(div) {
		div.style.backgroundColor = "";
	}
	
	// 把div提示字段填充到搜索框中
	function writeText(div){
		// 获取搜索框元素
		var searchElement = document.getElementById("name");
		searchElement.value = div.innerHTML;
		div.parentNode.style.display="none"; //div中点击后隐藏
	}
</script>


<div id="divmenu">
	<a
		href="${pageContext.request.contextPath}/showProductByPage?category=文学">文学</a>
	<a
		href="${pageContext.request.contextPath}/showProductByPage?category=生活">生活</a>
	<a
		href="${pageContext.request.contextPath}/showProductByPage?category=计算机">计算机</a>
	<a
		href="${pageContext.request.contextPath}/showProductByPage?category=外语">外语</a>
	<a
		href="${pageContext.request.contextPath}/showProductByPage?category=经营">经管</a>
	<a
		href="${pageContext.request.contextPath}/showProductByPage?category=励志">励志</a>
	<a
		href="${pageContext.request.contextPath}/showProductByPage?category=社科">社科</a>
	<a
		href="${pageContext.request.contextPath}/showProductByPage?category=学术">学术</a>
	<a
		href="${pageContext.request.contextPath}/showProductByPage?category=少儿">少儿</a>
	<a
		href="${pageContext.request.contextPath}/showProductByPage?category=艺术">艺术</a>
	<a
		href="${pageContext.request.contextPath}/showProductByPage?category=原版">原版</a>
	<a
		href="${pageContext.request.contextPath}/showProductByPage?category=科技">科技</a>
	<a
		href="${pageContext.request.contextPath}/showProductByPage?category=考试">考试</a>
	<a
		href="${pageContext.request.contextPath}/showProductByPage?category=生活百科">生活百科</a>
	<a href="${pageContext.request.contextPath}/showProductByPage"
		style="color:#FFFF00">全部商品目录</a>
</div>
<div id="divsearch">
	<form action="${pageContext.request.contextPath}/findProductBySearch"
		method="post">
		<table width="100%" border="0" cellspacing="0">
			<tr>
				<td style="text-align:right; padding-right:220px">
				Search <input
					type="text" name="name" class="inputtable" onkeyup="searchName();"
					id="name" /> 
					<input type="image" src="images/serchbutton.gif"
					border="0" style="margin-bottom:-4px">
				</td>
			</tr>
		</table>

	</form>
</div>
<div id="context1" style="display:block; border:1px solid red;background-color:white;width:128px; position:absolute;left:944px;top:135px;">
	
</div>

关于这个代码最后div中,left和top的位置问题,会随着不同浏览器和不同分辨率,这个红色的div框位置有点偏移,这个问题,就不管了。

项目全部代码请看github: https://github.com/Anthonyliu86/BookManagement_JavawebDemo

这篇代码的commit message为 “搜索框提示并点击填充完成