案例:实现百度搜索提示

分析:在输入框中输入词汇后,提示出以该关键字开头的存在数据库中的记录

一、搭建环境

1、定义首页

<body>
	<center>
		<input type="text" name="word" id="word"
			style="width: 600px; height: 50px; border: 1px solid; font-size: 20px;" />
		<input type="button" style="width: 100px; height: 60px" value="搜索" />
		<div id="div"
			style="position: relative; left: -54px; width: 600px; height: 400px; border: 1px solid blue; display: none;" />
	</center>
	</div>
</body>

2、定义数据库

###捕获键盘弹起

$(function(){
    $("#word").keyup(function() {
        alert("键盘弹起了..");
    })
});

JS请求

$(function(){
	$("#word").keyup(function(){
		//2、获取输入框的值 
		//var word = $("#word").val();
		//this  对应就是执行这个方法的那个对象, $("#word")
		var word = $(this).val();
		if(word==""){
			$("#div").hide();
		}else{
			//3. 请求数据。
			$.post("FindWordsServlet",{word:word},function(data,status){
				$("#div").show();
				$("#div").html(data);
			});
		}
	})
});

Servlet代码

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		
	try {
		//1. 先获取参数
		String word = request.getParameter("word");
		//2. 让dao执行查询
		WordDao dao = new WordDaoImpl();			
		List<WordBean> list = dao.findWords(word);

		request.setAttribute("list", list);
		//3. 返回数据
		response.setCharacterEncoding("text/html;charset=utf8");
		request.getRequestDispatcher("list.jsp").forward(request, response);
			
			
	} catch (SQLException e) {
		e.printStackTrace();
	}	
}

list.jsp代码

<body>
	<table style="width: 100%">
		<c:forEach items="${list}" var="wordBean">
			<tr>
				<td>${wordBean.words}</td>
			</tr>
		</c:forEach>
	</table>
</body>

dao实现

public List<WordBean> findWords(String word) throws SQLException {
	QueryRunner runner = new QueryRunner(JDBCUtil.getDataSource());
		
	String sql = "select * from words where words like ? limit ?";
		
	return runner.query(sql, new BeanListHandler<WordBean>(WordBean.class),word+"%",10);
}

猜你喜欢

转载自blog.csdn.net/HYN205/article/details/83780453