该 servlet的 应该返回自动完成数据作为JSON。有几个选项,我选择了一个包含带有标签/值属性的对象的数组:
@WebServlet("/autocomplete/*")public class AutoCompleteServlet extends HttpServlet { @Override protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { final List<String> countryList = new ArrayList<String>(); countryList.add("USA"); countryList.add("Pakistan"); countryList.add("Britain"); countryList.add("India"); countryList.add("Italy"); countryList.add("Ireland"); countryList.add("Bangladesh"); countryList.add("Brazil"); countryList.add("United Arab Emirates"); Collections.sort(countryList); // Map real data into JSON response.setContentType("application/json"); final String param = request.getParameter("term"); final List<AutoCompleteData> result = new ArrayList<AutoCompleteData>(); for (final String country : countryList) { if (country.toLowerCase().startsWith(param.toLowerCase())) { result.add(new AutoCompleteData(country, country)); } } response.getWriter().write(new Gson().toJson(result)); }}要返回自动完成数据,可以使用以下帮助程序类:
class AutoCompleteData { private final String label; private final String value; public AutoCompleteData(String _label, String _value) { super(); this.label = _label; this.value = _value; } public final String getLabel() { return this.label; } public final String getValue() { return this.value; }}因此在servlet中,实际数据被映射为适合jQuery自动完成的形式。我选择了Google GSON将结果序列化为JSON。
有关:
- 使用AJAX源代码和appendTo了解并实现Jquery自动完成功能
对于 HTML文档 (在.jsp中实现),请选择正确的库,样式表和样式:
<html> <head> <script type="text/javascript" src="http://pre.jquery.com/jquery-1.10.2.js"> </script> <script type="text/javascript" src="http://pre.jquery.com/ui/1.10.3/jquery-ui.js"> </script> <link rel="stylesheet" href="http://pre.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" /> <script type="text/javascript" src="autoComplete.js"> </script> </head> <body> <form> <div > <label for="country">Country: </label> <input id="country" /> </div> </form> </body></html>
相关:jQuery自动完成演示
我把 Javascript函数 放在一个单独的文件中
autoComplete.js:
$(document).ready(function() { $(function() { $("#country").autocomplete({ source: function(request, response) { $.ajax({ url: "/your_webapp_context_here/autocomplete/", type: "POST", data: { term: request.term }, dataType: "json", success: function(data) { response(data); } }); }}); });});自动完成功能使用AJAX请求来调用servlet。由于servlet是合适的,因此它可以原样用于响应。
有关:
- jQuery自动完成小部件
- jQuery ajax函数



