String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
百度搜索
巴莫搜索
//加载
$(function(){
//派发事件
$("#kid").keyup(function(){
//获取用户输入的关键字
var $keywords = $(this).val();
if ($keywords != null && $keywords !="") {
//清空div
$("#did").html("");
var url = "${pageContext.request.contextPath}/ajaxSearch";
var param = {"keywords":$keywords};
$.post(url,param,function(data){
//不为空的时候切割字符串
if (data != null) {
$(data).each(function(index,n){
$("#did").append("
"+n+"
");
})
$("#did").show();
}
},"json")
}else{
//内容为空时,将div隐藏起来
$("#did").hide();
}
});
});
public class AjaxSearchServlet extends HttpServlet {
private static final long serialVersionUID = -3112366969977240031L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//获取请求参数
String keywords = request.getParameter("keywords");
//System.out.println(keywords);
try {
List list = new SearchService().findKeywords4Ajax(keywords);
//System.out.println(list.toString());
if (list != null && list.size() >0 ) {//判断list是否为空
String jsonString = JSON.toJSONString(list);
System.out.println(jsonString);
response.setCharacterEncoding("utf-8");
response.getWriter().print(jsonString);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public class SearchService {
public List findKeywords4Ajax(String keywords) throws SQLException {
return new SearchDao().findKeywords4Ajax(keywords);
}
}
public class SearchDao {
public List findKeywords4Ajax(String keywords) throws SQLException {
QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "select keywords from t_keywords where keywords like ? limit 5";
//ColumnListHandler:将结果集中某一列的数据存放到List中。
return qr.query(sql, new ColumnListHandler("keywords"),"%"+keywords+"%");
}
}