Servlet:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;UTF-8");
request.setCharacterEncoding("UTF-8");
try {
String content = request.getParameter("contentword");
System.out.println(content);
TestService testService = new TestService();
List<Word> list = testService.findWord(content);
request.setAttribute("list", list);
request.getRequestDispatcher("/ajaxsearch/info.jsp").forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
Service:
public List<Word> findWord(String content) throws SQLException {
TestDao testDao = new TestDao();
return testDao.findWord(content);
}
Dao:
public List<Word> findWord(String content) throws SQLException {
System.out.println(content);
QueryRunner queryRunner = new QueryRunner(C3P0JDBCUtils.getDataSource());
String sql = "select * from user2 where word like ? limit 5";
List<Word> list = queryRunner.query(sql, new BeanListHandler<Word>(Word.class),content+"%");
return list;
}
首页ajax_search.jsp:
<body>
<center>
<h1>Search</h1>
<input type="text" id="contentword" name="contentword" style="width:400px;height:25px;" >
<input type="button" id="search" name="content" value="Search" style="width:80px;height:25px;">
<div id="d1" style="display:none;position:absolute;top:120px;left:440px;border:1px solid gray;width:400px;height:200px;"></div>
</center>
</body>
触发函数js:
$(function() {
$("#contentword").keyup(function() {
var content = $(this).val();
if(content != "") {
$.post("/WebTest/TestServlet",{"contentword":content},function(data) {
$("#d1").show().html(data);
});
} else {
$("#d1").hide();
}
});
});
info.jsp 接收servlet转发来的值进行遍历:
<table border="0" width="100%">
<c:forEach var="w" items="${ list }">
<tr>
<td>
${ w.word }
</td>
</tr>
</c:forEach>
</table>