第一步:
创建表单,放搜索框
第二步:
写JS
第三步:
在Web层创建Servlet,使用的gson转换的json格式,需要导包
public class SearchWordServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获得关键字 String word = request.getParameter("word"); //查询改关键字的所有商品 UserService service = new UserService(); List userList = null; try { userList = service.findUserByWord(word); } catch (SQLException e) { e.printStackTrace(); } //[{"username":"admin","phone":"17805054371","role":"超级管理员"...},{},{}...] //使用json的转换工具 /*1、JSonlib JSONArray fromObject = JSONArray.fromObject(userList); String string = fromObject.toString(); System.out.println(string); */ Gson gson = new Gson(); String json = gson.toJson(userList); response.setContentType("texy/html;charset=UTF-8"); response.getWriter().write(json); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); }}
第四步:
创建Service
public class UserService { public List findUserByWord(String word) throws SQLException { UserDao dao = new UserDao(); return dao.findUserByWord(word); }}
第五步:
创建Dao,使用的C3P0和DBUtils
public class UserDao { public List findUserByWord(String word) throws SQLException { QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource()); String sql = "select * from user where username like ? limit 0,8"; List query = runner.query(sql,new ColumnListHandler("username"),"%"+word+"%"); return query; }}
第六步:
完成并测试