使用Html标记和servlet自动完成

时间:2015-01-28 15:06:48

标签: java html servlets autocomplete

我试图通过从文件中读取文本来进行自动完成。它在秋千上运行良好。我想在服务器上运行它。已经使用了Html标签和servlet,但是当我输入查询后输入它显示我的匹配列表 如果我使用线程或任何Html标记进行自动完成,如何使其自动完成。我对编码不太了解。请帮帮我 这是我的servlet代码

NewServlet.java

public class NewServlet extends HttpServlet {

 public NewServlet() {

    }
 String json;

   ArrayList<String> match = new ArrayList<String>();

   protected void doGet(HttpServletRequest request, HttpServletResponse  response)
        throws ServletException, IOException {
    response.setContentType("text/html");

    //  response.setContentType("application/json");
    AutoTest1 t = new AutoTest1();
    ArrayList<String> words = new ArrayList<>();
    Trie suggestions = new Trie();
    String fileName =  "C:/Users/USER/Documents/NetBeansProjects/HelloWorld/web/WEB-INF/aol.txt";
    words = t.readWordsFromFile(fileName);
    Trie trie = new Trie();

    for (String word : words) {
        trie.insert(word);
    }
    suggestions = trie;
    try (PrintWriter out = response.getWriter()) {

        Gson gson = new Gson();

        String prefix = request.getParameter("term");

        ArrayList<String> matchingSuggestions = suggestions.getAllPrefixMatches(prefix);

        //final List<AutoCompleteData> result = new ArrayList<AutoCompleteData>();
        for (String suggestion : matchingSuggestions) {
            json = gson.toJson(suggestion);
            // result.add(new AutoCompleteData(suggestion,suggestion));

        }
          response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        //  response.getWriter().write("<option>"+new Gson().toJson(result)+"<option>");      // Write response body.

        response.getWriter().write(json);
       }

    }

  }

autocomplete.jsp

<html>
<head>
<script      src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
 </script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script type="text/javascript" src="js/jquery.autocomplete.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(function() {
        $("#search").autocomplete({     
        source : function(request, response) {
        $.ajax({
                url : "NewServlet",
                type : "GET",
                data : {
                        term : request.term
                },
                dataType : "json",
                success : function(data) {
                        response(data);
                }
             });
            }
          });
       });
    });
    </script>
  </head>
<body>
      <div class="search-container">
            <div class="ui-widget">
            <input type="text" id="search" name="search" class="search" />
            </div>
      </div>
 </body>
 </html>

1 个答案:

答案 0 :(得分:0)

您始终可以在web.xml中定义新的servlet,并在AJAX调用中调用它来返回建议。

如果你正在使用jQuery,你可以做这样的事情

<强> main.jsp中

<input type="text" list="suggestions" class="inputBox"/>

<datalist id="suggestions">
  <option value=" Loading...">
</datalist>

<script>
    $(document).ready(function(){
      $('.inputBox').on('keyup',function(){
         $.ajax({
            url : 'yourServletAction'
            data : {'query' : $(this).val()}
         }).done(function(data,jqXHR){
             $('#suggestions').html(data);
         });
      }); 
    )};
</script>

doGet()的服务器端,基于query参数,您将填充ArrayList中的建议并将其另存为此类请求属性

protected void doGet(HttpServletRequest request, HttpServletResponse   response) throws ServletException,IOException{
        String prefix =request.getParameter("query");
        ArrayList<String> matchingSuggestions =  suggestions.getAllPrefixMatches(prefix);

        request.setAttribute("suggestions",matchingSuggestions);
        RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/suggest.jsp");
        rd.forward(request,response);

    }

现在控件转到suggest.jsp,我们可以使用JSTL(从here下载)循环遍历列表并发送选项。事实上你可以使用杰克逊图书馆发回JSON,但我感觉到目前它的消化太多了

<强> suggest.jsp

<c:forEach items="${suggestions}" var="suggestion">
   <option value="${suggestion}" />
</c:forEach>

这应该给你一些开始:)