Servlet+Ajax实现搜索智能提示及遇到的问题

Servlet+Ajax实现搜索智能提示的案例网上很多,先贴上自己使用的代码。

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>smart search</title>
<style type="text/css">
.mouseOver {
    background: #00B2EE;
    color: white;
    width: 200px;
}
.mouseOut {
    background: #EDEDED;
    width: 200px;
}
</style>
<script type="text/javascript">
        var xmlHttp;
    //获取用户输入的关联信息的函数
    function getMoreContens() {
        //获取用户输入
        var content = document.getElementById("keyWords").value;
        if (content == "") {
            clearContent();
            return;
        }
        xmlHttp = createXmlHttp();
        //给服务器发送数据
        var url = "search?keyword="+encodeURI(content); 
        xmlHttp.open("GET",url,true);
        xmlHttp.onreadystatechange =     //回调函数
            function callback()
        {
            if(xmlHttp.readyState == 4)
                {
                if(xmlHttp.status == 200){
                    var result = decodeURIComponent(xmlHttp.responseText);
                    var json = eval("("+result+")");
                    clearContent(json);
                    intelliSense(json);
                }
                }
        };
        /*
            xmlhttp的send是传递参数用的,但是只有在使用post方式提交请求的时候才有用
            如下:
            xmlhttp.open("post",url,true); 
            ...
            xmlhttp.send("data=data&data2=data2");
             
            用get的话一般就是:
            xmlhttp.open("get",url,true); 
            ...
            xmlhttp.send(null);
        */
        xmlHttp.send(null);
    }
    
    //创建XMLHttpRequest
    function createXmlHttp()
    {
        var xmlHttp;
        if(window.XMLHttpRequest)
            {
            xmlHttp = new XMLHttpRequest();
            //兼容某些Mozilla浏览器的响应头,强制设置为text/xml,具体参看:http://www.cnblogs.com/perseverancevictory/p/3690769.html
               if(xmlHttp.overrideMimeType){  
                   xmlHttp.overrideMimeType("text/xml");
               }
            }
        //兼容IE
        else if(window.ActiveXObject)
            {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            if(!xmlHttp)
                {
                xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
                }
            }
        return xmlHttp;
    }

    function clearContent()
    {
        var contentTableBody = document.getElementById("content_table_body");
        var size = contentTableBody.childNodes.length;
        for(var i=size-1;i>0;i--)
            {
            contentTableBody.removeChild(contentTableBody.childNodes[i]);
            }
    }
    function intelliSense(json)
    {
        //获取关联数据的长度
        var size = json.length;
        for(var i=0;i<size;i++)
            {
            var nextNode = json[i];
            var tr= document.createElement("tr");
            var td= document.createElement("td");
            tr.setAttribute("border", "0");
            tr.setAttribute("bgcolor", "#EDEDED");
            td.setAttribute("width", "200px");
            td.onmouseover=function()
            {
                this.className = 'mouseOver';
            }
            td.onmouseout=function()
            {
                this.className = 'mouseOut';
            }
            td.onclick=function()
            {
                document.getElementById("keyWords").value=this.innerText;
            }
            var text=document.createTextNode(nextNode);
            td.appendChild(text);
            tr.appendChild(td);
            document.getElementById("content_table_body").appendChild(tr);
            }
    }
</script>
</head>
<body>
    <div>
        <input type="text"  name="keyWords" id="keyWords"  style="width:200px; height:20px;" onkeyup="getMoreContens()" onfocus="getMoreContens()" onblur="clearContent()" /> <input
            type="button" id="button" value="百度一下">
            <div id="popDiv">
            <table id="content_table">
                <tbody id="content_table_body">
                </tbody>
            </table>
        </div>
    </div>
</body>
</html>

  web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet-mapping>
    <servlet-name>search</servlet-name>
    <url-pattern>/search</url-pattern>
</servlet-mapping>
<servlet>
    <description>搜索</description>
    <servlet-name>search</servlet-name>
    <servlet-class>com.baorant.search.SearchServlet</servlet-class>
</servlet> 
</web-app>

  SearchServlet类

package com.baorant.search;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

public class SearchServlet extends HttpServlet {

    private static List<String> keyWordList = new ArrayList<String>();
    static {
        // 模拟数据
        keyWordList.add("yanwei");
        keyWordList.add("yantian");
        keyWordList.add("yanpeng");
        keyWordList.add("yanweichao");
        keyWordList.add("yanweiqi");
        keyWordList.add("yanyurong");
        keyWordList.add("yanmeirong");
        keyWordList.add("yanweichen");
        keyWordList.add("电影");
        keyWordList.add("电影 66ys");
    }
    private static final long serialVersionUID = 1L;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        String keyWord = req.getParameter("keyword");
        System.out.println(keyWord);
        List<String> list = keyWord==null?new ArrayList<String>():getDatas(keyWord);
        String json = JSON.toJSONString(list);
        //防止乱码
        String encodeJSON = URLEncoder.encode(json,"UTF-8");
        resp.getWriter().write(encodeJSON);
    }

    public static List<String> getDatas(String keyWord) {
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < keyWordList.size(); i++) {
            if (keyWordList.get(i).contains(keyWord)) {
                list.add(keyWordList.get(i));
            }
        }
        return list;
    }
}

  已直接从工程build path导入fastjson-1.2.2.jar,但仍然报错:java.lang.ClassNotFoundException: com.alibaba.fastjson.JSON

解决方法:将之前直接导入的jar包复制放入项目中lib目录下,重新编译,成功

 

posted on 2018-05-21 05:02  baorant  阅读(245)  评论(0编辑  收藏  举报

导航