输入框页面提示

Servlet:
public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;UTF-8");
        request.setCharacterEncoding("UTF-8");
        try {
            //接收文本框输入的值
            String content = request.getParameter("contentword");
            System.out.println(content);
            TestService testService = new TestService();
            List<Word> list = testService.findWord(content);

            request.setAttribute("list", list);
            request.getRequestDispatcher("/ajaxsearch/info.jsp").forward(request, response);//转发到jsp进行遍历
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
Service:
public List<Word> findWord(String content) throws SQLException {
        TestDao testDao = new TestDao();
        return testDao.findWord(content);
    }
Dao:
public List<Word> findWord(String content) throws SQLException {
        System.out.println(content);
        QueryRunner queryRunner = new QueryRunner(C3P0JDBCUtils.getDataSource());
        String sql = "select * from user2 where word like ? limit 5";
        List<Word> list = queryRunner.query(sql, new BeanListHandler<Word>(Word.class),content+"%");
        return list;
    }
首页ajax_search.jsp:
<body>
    <center>
        <h1>Search</h1>
        <input type="text" id="contentword" name="contentword" style="width:400px;height:25px;" >
        <input type="button" id="search" name="content" value="Search" style="width:80px;height:25px;">
        <div id="d1" style="display:none;position:absolute;top:120px;left:440px;border:1px solid gray;width:400px;height:200px;"></div>
    </center>
  </body>
触发函数js:
$(function() {
    //为文本框绑定事件
    $("#contentword").keyup(function() {
        //获取文本框的值
        var content = $(this).val();
        //异步发送请求
        if(content != "") { //文本框有值
            $.post("/WebTest/TestServlet",{"contentword":content},function(data) {
                //将内容显示到div上
                $("#d1").show().html(data);
            });
        } else { //文本框没值
            //隐藏div
            $("#d1").hide();
        }
    });
});
info.jsp 接收servlet转发来的值进行遍历:
<table border="0" width="100%">
    <c:forEach var="w" items="${ list }">
        <tr>
            <td>
                ${ w.word }
            </td>
        </tr>
    </c:forEach>
</table>

猜你喜欢

转载自blog.csdn.net/sinat_40662281/article/details/80466387
今日推荐