1、jsp页面
<script type="text/javascript"> function overFn(obj){ $(obj).css("background","#DBEAF9"); } function outFn(obj){ $(obj).css("background","#fff"); } function clickFn(obj){ $("#search").val($(obj).html()); $("#showDiv").css("display","none"); } function searchWord(obj){ var word = $(obj).val(); var content = ""; $.get( "${pageContext.request.contextPath}/searchServlet", {"word":word}, function(data){ if(data.length>0){ for(var i=0;i<data.length;i++){ content+="<div style='padding:5px;cursor:pointer' onclick='clickFn(this)' " + "onmouseover='overFn(this)' onmouseout='outFn(this)'>"+data[i]+"</div>"; } $("#showDiv").html(content); $("#showDiv").css("display","block"); } }, "json" ); } </script>
(1)从输入框中获取输入的数据后将数据封装为json。
(2)利用jq封装的ajax中的get方法,将获得的数据发送到服务器,并获取服务器的返回的数据将其转换为json类型。
<div > <input id="search" type="text" placeholder="Search" onkeyup="searchWord(this)"> <div id="showDiv" style="display:none; position:absolute;z-index:1000;background:#fff; 179px;border:1px solid #ccc;"> </div> </div>
2、web层、service层
(1)servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String word = request.getParameter("word"); SearchService service = new SearchService(); List<Object> productList = null; try { productList = service.findProductByWord(word); } catch (SQLException e) { e.printStackTrace(); } Gson gson = new Gson(); String json = gson.toJson(productList); response.setContentType("text/html;charset=UTF-8"); response.getWriter().write(json); }
将从jsp页面获取到的数据作为函数的参数,经service层和dao层从数据库中获取数据,将数据转化为字符串(需要导入相应的jar包),然后将数据返回给get()方法中的回调函数。
(2)service层:
public List<Object> findProductByWord(String word) throws SQLException { SearchDao dao = new SearchDao(); return dao.findProductByWord(word); }
3、dao层
public List<Object> findProductByWord(String word) throws SQLException { Connection con = C3p0Utils.getConnection(); QueryRunner qr = new QueryRunner(); String sql = "select * from product where pname like ? limit 0,8"; List<Object> query = qr.query(con,sql, new ColumnListHandler("pname"), "%"+word+"%"); return query; }
通过sql语句从数据库查找满足条件的数据,将数据返回到service层并最终到达jsp页面。
4、效果演示
这些数据是从数据库中读取的。