代码总结:文本栏关键字搜索功能实现

  • 需求:根据关键字搜索功能(%通配符)
<div id="rightquestion">
    <input type="text" placeholder="请输入查询关键字"/>
    <a href="#"><img src="img/ic_search.svg"/></a>
</div>
<script>
    $("#rightquestion").mouseover(function(){
    var keyWord = $("#rightquestion input").val();
    $("#rightquestion a").attr("href","search.jsp?keyWord="+keyWord);//传递关键字
});
</script>
<%
//jsp脚本
String keyWord = request.getParameter("keyWord");
if(keyWord == ""){
    request.setAttribute("schList",null);
}else{
    QuestionService qService = QuestionService.getService();
    List<QuestionShow> schList = qService.searchQuestion(keyWord);
    request.setAttribute("schList",schList);
    request.setAttribute("keyWord",keyWord);
}
%>
//数据库操作
public List<QuestionShow> searchQuestion(String keyWord){
        List<QuestionShow> qList = new ArrayList<QuestionShow>();
        Connection conn = DBHelper.linkToDB();
        PreparedStatement pcmd = null;
        ResultSet rs = null;
        String sql = "SELECT a.qid,a.title,a.tags,a.content,b.nickName,b.photo,a.pubtime,a.votes,a.answers,a.visitors,a.type ";
        sql += "FROM question AS a ";
        sql += "LEFT JOIN USER AS b ";
        sql += "ON a.publisher=b.id ";
        sql += "WHERE title LIKE ? ";
        sql += "OR tags LIKE ? ";
        sql += "OR content LIKE ? ";
        try {
            pcmd = conn.prepareStatement(sql);
            pcmd.setString(1, "%"+keyWord+"%");
            pcmd.setString(2, "%"+keyWord+"%");
            pcmd.setString(3, "%"+keyWord+"%");
            rs = pcmd.executeQuery();
            while(rs.next()){
                int qid = rs.getInt(1);
                String title = rs.getString(2);
                String rsTags = rs.getString(3);
                String[] tags = rsTags.split(",");
                String content = rs.getString(4);
                String publisher = rs.getString(5);
                String photo = rs.getString(6);
                String pubtime = rs.getString(7).substring(0, 16);
                int votes = rs.getInt(8);
                int answers = rs.getInt(9);
                int visitors = rs.getInt(10);
                String type = rs.getString(11);
                qList.add(new QuestionShow(qid,title,tags,content,publisher,photo,pubtime,votes,answers,visitors,type));    
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally{
            DBHelper.close(conn, pcmd, rs);
        }
        return qList;
    }   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值