input.jsp <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<style>
ul
{
list-style: none
} </style> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<script>
var xmlHttpRequest = null;
//ajax的服务器验证
function send_ajax_request()
{
var word = document.getElementById("word").value; //获得控件的输入值
if(word.length==0) //如果搜索词为空,则不发送请求
return; //a js中创建ajax请求对象
xmlHttpRequest = new XMLHttpRequest();
//b 通过open方法连接服务器 var url = "HotWordServlet";
xmlHttpRequest.open("post",url,true);
xmlHttpRequest.
setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8"); //c 通过onreadystatechange注册“回调函数”
xmlHttpRequest.onreadystatechange = doreceive; //d 通过send发送请求数据 xmlHttpRequest.send("word="+word)//请求报文的body,即post的参数。
} //ajax响应后自动回调的方法!
function doreceive()
{
if(xmlHttpRequest.readyState==4&&xmlHttpRequest.status==200)
{
//将div变为可见
document.getElementById("tip").style.display = ""; //将div的内部html替换成服务器响应的内容
document.getElementById("tip").innerHTML = xmlHttpRequest.responseText;
}
} //将该id对应li进行高亮,其他的li变为正常
function highlight(id)
{
//获取所有的li标签
var lis = document.getElementsByTagName("li");
for(var i=0;i<lis.length;i++)
{
lis[i].style.backgroundColor = "white";
}
var li = document.getElementById(id);
li.style.backgroundColor = "yellow";
}
//点击id对应的提示行
function doclick(id)
{
//1 将该li的文字放到输入框中
var li = document.getElementById(id);
document.getElementById("word").value = li.innerText;
//2 隐藏提示框
document.getElementById("tip").style.display = "none";
}
</script>
<body>
<input id="word" name="word" style="position: absolute; left: 200px;top: 200px;width: 200px;height: 20px;" onkeyup="send_ajax_request()">
<input type="button" style="position: absolute; left: 400px;top: 200px;width: 50px;height: 20px;"
value="搜索"/>
<div id="tip" style="position: absolute; left: 200px;top: 220px;width: 200px;height: 100px;background-color:white;border-color: gray;border-style: solid;display: none"> </div>
</body>
</html>
HotWordServlet: import java.io.IOException;
import java.io.PrintWriter;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class HotWordServlet extends HttpServlet { //模拟“热词表”,key为关键词,value为搜索次数
private Map<String,Integer> hotwords = new HashMap<String,Integer>(); /**
* Constructor of the object.
*/
public HotWordServlet() {
initHotWords();
}
//初始化热词
private void initHotWords()
{
hotwords.put("马尔代夫", 10000);
hotwords.put("马云", 9000);
hotwords.put("马云的老婆", 8000);
hotwords.put("马蓉", 12000);
hotwords.put("王宝强", 8000);
hotwords.put("王者荣耀", 7500);
hotwords.put("王欧", 7000);
hotwords.put("王思聪", 6000);
hotwords.put("王子文", 5000);
} //内部类,自定义比较器,实现对热词的字符串按照搜索次数进行倒序
class MyHotWordComparator implements Comparator<String>
{ public int compare(String o1, String o2) {
//只要热词1的搜索次数比热词2大,认为在set中是“大的”
if(hotwords.get(o1)>hotwords.get(o2))
return 1;
else
return -1;
} }
//从热词库中,查找以指定搜索词开头的热词。并按热度排序
private Set<String> findHotWords(String begin)
{
//"abcd".indexOf("b") ==》1
//"abcd".indexOf("a") ==》0 Set<String> result = new TreeSet<String>(new MyHotWordComparator());
//按遍历热词库
for(String key:hotwords.keySet())
{
if(key.indexOf(begin)==0) //子串的位置是0
{
result.add(key); //由于使用自定义比较器,所以"索引"是有序的
}
}
return result;
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
} /**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { doPost(request,response);
} /**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//1 读取请求参数的中“搜索词"
String word = request.getParameter("word");
//2 去热词库匹配,获得满足的所有热词set
Set<String> result = findHotWords(word);
//3 组成div中的子html并返回
String html = "<ul>";
int i = 1;
for(String str:result)
{
//给li的id进行编号,并且制定鼠标移入和点击事件
html += "<li id='t"+i+"' onmouseover='highlight(this.id)' " +
"onclick = 'doclick(this.id)'>"+str+"</li>";
i++;
}
html+="</ul>";
PrintWriter out = response.getWriter();
out.print(html);
out.flush();
out.close();
} /**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
} }