做软件都要从用户的角度来做,怎么样让用户输入的更少,体验更好,我们就应该怎么来做,也就是需求驱动,客户都是大爷!题外话说完了,步入正题,本文实现在查询时输入查询条件时,自动提示数据库中包含改值所有记录(注意,我这里用的是包含,not start,not end,这是跟mysql的模糊查询相关的),看下实现效果:
[{"label":"山东省青岛第二中学","value":"山东省青岛第二中学"},{"label":"山东省青岛第六十三中学","value":"山东省青岛第六十三中学"}]其中label属性用于显示在autocomplete弹出菜单,而value属性则是选中后给文本框赋的值。
public class AddressAutocompleteServlet extends HttpServlet { /** * 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 { // 设置输出内容格式和编码 response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); // 设置接收参数编码格式 response.setCharacterEncoding("utf-8"); // 构造sql查询语句 String schoolAddress = new String(request.getParameter("term") .getBytes("ISO-8859-1"), "UTF8"); String sql = "select address from school where address like " + "\'" + "%" + schoolAddress + "%" + "\'"; PoiDBBean poiDBBean = new PoiDBBean(); // 查询结果以json数据格式返回 JSONArray array = new JSONArray(); try { ResultSet resultSet = poiDBBean.query(sql); while (resultSet.next()) { JSONObject object = new JSONObject().element("label", resultSet.getString(1)).element("value", resultSet.getString(1)); array.add(object); } out.println(array.toString()); System.out.println(array.toString()); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { poiDBBean.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }autocomplete默认输入的参数名为term,在浏览器中输入:http://127.0.0.1:8080/taxGIS/servlet/AddressAutocompleteServlet?term=崂山区松岭路,会出现返回的json数据,如下:
$("#schoolAddress").autocomplete({ source: "http://127.0.0.1:8080/taxGIS/servlet/AddressAutocompleteServlet", minLength: 3 });博客还是要坚持写啊,这是总结沉淀的过程。劲量写的调理清楚,把遇到的问题和解决方案都记录下来,以便日后查找,也为帮到需要的人
OpenLayers学习笔记9——使用servlet与jquery-ui实现自动提示输入
原文:http://blog.csdn.net/giser_whu/article/details/46586121