分析:在輸入框中輸入詞彙後,提示出以該關鍵字開頭的存在數據庫中的記錄
一、搭建環境
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);
}