新闻发布系统
3.3.3 搜索新闻:
功能:根据关键字搜索新闻
实现:接收搜索关键字,对新闻进行模糊搜索,并将搜索结果封装到一个PageModel的Bean中,该Ban存放了搜索结果的所有信息,返回至JSP页面后即可取出相应信息并显示。
public PageModel<News> searchNews(String key,int pageNow){ PageModel<News> newsModel = new PageModel<News>(); ArrayList<News> newsList = new ArrayList<News>(); int totalRecord=0; try {
con = DBConnector.getConnection();
ps = con.prepareStatement("select count(*) from news where news_title like ?");
ps.setString(1, "%"+key+"%"); rs = ps.executeQuery(); if(rs.next()){
totalRecord = rs.getInt(1); }
ps = con.prepareStatement("select * from news where news_title like ? limit ?,?");
ps.setString(1, "%"+key+"%");
ps.setInt(2, pageSize*(pageNow-1)); ps.setInt(3, pageSize); rs = ps.executeQuery(); while(rs.next()){
News news = new News();
news.setNews_id(rs.getInt(1));
news.setNews_type(rs.getString(2)); news.setNews_keys(rs.getString(3)); news.setNews_origin(rs.getString(5)); news.setNews_title(rs.getString(7)); news.setNews_time(rs.getString(9));
newsList.add(news); }
} catch (SQLException e) { e.printStackTrace(); }finally{
DBConnector.free(rs, ps, con); }
newsModel.setList(newsList);
newsModel.setPageNow(pageNow);