程式碼總結:文字欄關鍵字搜尋功能實現
阿新 • • 發佈:2018-12-09
- 需求:根據關鍵字搜尋功能(%萬用字元)
<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;
}