需求:
一般列表页上面会有一个查询框,有各种的查询条件组合,一般都采用模糊查询方式 ,以下以自己做的实例来说明一下实现方法:
需要实现的界面原型:要满足条件:
1、单选分类,点GO按扭
2、单独输入标题关键字,点GO按扭
3、选择分类,再输入关键字,点GO按扭
我这里用了MVC分层模式来进行的,所以一步步讲解吧,上源码:
因为我一个class里写了很多不同的业务,所以帖代码只帖当前步
dao层:
1 //当前页显示的新闻信息pageNo 当前页码,pagePerCount是每页多少条数据 2 public List<NewsDetail> getPageNewsList(int pageNo,int pagePerCount,String where);
daoImpl层:
这里方法中加的参数是where,因为我不确定前台可能有几个模糊查询的条件,所以这里只能用个整体的字符串来定义,到时候用StringBuffer来拼就行
这里注意一下字符串拼接加变量的写法
1 public List<NewsDetail> getPageNewsList(int pageNo, int pagePerCount,String where) { 2 List<NewsDetail> newslist =new ArrayList<NewsDetail>(); 3 String sql = "select d.id,d.title,d.author,d.summary,d.content,d.picPath,d.createDate,d.modifyDate," + 4 "d.createDate,d.categoryId,c.name as categoryname from news_detail as d,news_category as c" + 5 " where c.id=d.categoryId and d.status=1 "+where+"order by d.createDate desc limit ?,?"; 6 Object[] params ={(pageNo-1)*pagePerCount,pagePerCount}; 7 if(this.getconnection()){ 8 ResultSet rs = this.executeQuery(sql, params); 9 try { 10 while(rs.next()){ 11 NewsDetail news = new NewsDetail(); 12 int id = rs.getInt("id"); 13 String title1 = rs.getString("title"); 14 String author =rs.getString("author"); 15 int categoryId = rs.getInt("categoryId"); 16 String categoryname=rs.getString("categoryname"); 17 String summary = rs.getString("summary"); 18 String content = rs.getString("content"); 19 String picPath =rs.getString("picPath"); 20 Timestamp createDate =rs.getTimestamp("createDate"); 21 Timestamp modifyDate =rs.getTimestamp("modifyDate"); 22 news.setId(id); 23 news.setCategoryId(categoryId); 24 news.setAuthor(author); 25 news.setCategoryname(categoryname); 26 news.setContent(content); 27 news.setSummary(summary); 28 news.setPicPath(picPath); 29 news.setCreateDate(createDate); 30 news.setModifyDate(modifyDate); 31 news.setTitle(title1); 32 newslist.add(news); 33 34 } 35 } catch (SQLException e) { 36 e.printStackTrace(); 37 }finally{ 38 this.clossconnection(); 39 } 40 } 41 return newslist; 42 }
service接口:
1 //当前页显示的新闻信息pageNo 当前页码,pagePerCount是每页多少条数据 2 public List<NewsDetail> getPageNewsList(int pageNo,int pagePerCount,String where);
serviceImpl接口实现类:
因为业务比较简单,所以代码也很简单哈,service只是调一下dao即可
1 public class NewsServiceImpl implements NewsService { 2 private NewsDao newsdao =null; 3 public NewsServiceImpl(){ 4 newsdao=new NewsDaoImpl(); 5 newscategory1 =new NewsCategoryDaoImpl(); 6 } 7 public int getNewsCount(String where) { 8 return newsdao.getNewsCount(where); 9 } 10 }
以下是重点,套页面JSP+Servlet
newsDetailList.jsp:我把样式那些都省略了,只列出整体的页面框架元素
1 <div class="main-content-right"> 2 <!--即时新闻--> 3 <div class="main-text-box"> 4 <div class="main-text-box-tbg"> 5 <div class="main-text-box-bbg"> 6 <form name ="searchForm" id="searchForm" action="<%=request.getContextPath() %>/servlet/newsListByLikeServlet" method="post"> 7 <div> 8 新闻分类: 9 <select name="categoryId"> 10 <option value="0">全部</option> 11 <c:forEach var="category" items="${categorylist }" varStatus="status"> 12 <option value=‘${category.id }‘ >${category.name }</option> 13 </c:forEach> 14 15 16 17 </select> 18 新闻标题<input type="text" name="title" id="title" value=‘‘/> 19 <button type="submit" class="page-btn" onclick="javascript:window.location.href=‘<%=request.getContextPath() %>/servlet/newsListByLikeServlet‘">GO</button> 20 <button type="button" onclick="addNews();" class="page-btn">增加</button> 21 <!--隐藏域,当前页码 --> 22 <input type="hidden" id="pageIndex" name="pageIndex" value="1"/> 23 24 <input type="hidden" name="pageSize" value="10"/> 25 26 </div> 27 </form> 28 <table cellpadding="1" cellspacing="1" class="admin-list"> 29 <thead > 30 <tr class="admin-list-head"> 31 <th align="center">新闻标题</th> 32 <th align="center">新闻类别</th> 33 <th align="center">作者</th> 34 <th align="center">创建时间</th> 35 <th align="center">操作</th> 36 </tr> 37 </thead> 38 39 <tbody> 40 <c:forEach var="news" items="${newsList}" varStatus="status"> 41 <tr <c:if test="${status.count%2==0 }"> class="admin-list-td-h2"</c:if>> 42 <td><a href=‘<%=request.getContextPath() %>/servlet/NewsViewServlet?id=${news.id }‘>${news.title }</a></td> 43 <td>${news.categoryname }</td> 44 <td>${news.author }</td> 45 <td><fmt:formatDate value="${news.createDate}" pattern="yyyy-MM-dd"/></td> 46 <td><a href=‘<%=request.getContextPath() %>/servlet/EditViewServlet?id=${news.id }‘>修改</a> 47 <a href="javascript:if(confirm(‘确认是否删除此新闻?‘)) location=‘<%=request.getContextPath() %>/servlet/DelNewsServlet?id=${news.id }‘">删除</a> 48 </td> 49 </tr> 50 </c:forEach> 51 52 53 <input type="hidden" id="totalPageCount" name="totalPageCount" value="${totalPageCount }"/> 54 </tbody> 55 56 </table> 57 <c:import url="rollPage.jsp"> 58 <c:param name="totalCount" value="${totalCount }"></c:param> 59 <c:param name="currentPageNo" value="${currentPageNo }"></c:param> 60 <c:param name="totalPageCount" value="${totalPageCount}"></c:param> 61 62 </c:import> 63 64 </div> 65 </div> 66 </div> 67 </div>
可以看出,我图1中的查询那块是一个form,HTML框架比较清晰,那么我的servlet要做的事就是:获取用户选择的select下拉框选择的分类和用户输入的title关键字
form表单提交的数据,我们可以在servlet通过getParameter方法来获取
NewsListByLike2代码如下:
1 public class NewsListByLike2 extends HttpServlet { 2 NewsService newsService =new NewsServiceImpl(); 3 4 @Override 5 protected void doGet(HttpServletRequest request, HttpServletResponse response) 6 throws ServletException, IOException { 7 StringBuffer sb =new StringBuffer(1024); 8 String title = request.getParameter("title"); 9 System.out.println("title============="+title); 10 if(title!=null && !"".equals(title)){ 11 sb.append(" and d.title like ‘%"+title+"%‘"); 12 } 13 14 String categoryId = request.getParameter("categoryId"); 15 System.out.println("categoryId============"+categoryId); 16 if(categoryId!=null && !"".equals(categoryId)){ 17 int categoryid=Integer.parseInt(categoryId); 18 sb.append(" and d.categoryId like ‘%"+categoryid+"%‘ "); 19 } 20 List<NewsCategory> categorylist = newsService.getcategorylist(); 21 int pageSize =5;//页面容量 22 int currentPageNo=1 ;//当前页码 23 String pageNo= request.getParameter("pageIndex");//获取当前页码隐藏域1 24 if(pageNo==null){ 25 currentPageNo=1; 26 }else{//不为空的话,就链接提交给我的当前页码即是用户请求的页码传给我的值,我赋予给我定的当前页码参数值 27 try{ 28 currentPageNo = Integer.parseInt(pageNo); 29 }catch(Exception e ){ 30 response.sendRedirect("error.jsp"); 31 } 32 33 } 34 35 int totalCount=newsService.getNewsCount(sb.toString());//总记录数 36 /*总页数*/ 37 38 int totalPageCount = totalCount/pageSize+1; 39 //首页和尾页的异常控制 40 if(currentPageNo<=0){ 41 currentPageNo =1; 42 }else if(currentPageNo>totalPageCount){ 43 currentPageNo=totalPageCount; 44 } 45 System.out.println("sql=============="+sb.toString()); 46 //显示每页新闻信息列表 47 List<NewsDetail> newsList = newsService.getPageNewsList(currentPageNo, pageSize, sb.toString()); 48 request.setAttribute("currentPageNo", currentPageNo); 49 request.setAttribute("pageSize", pageSize); 50 request.setAttribute("totalPageCount", totalPageCount); 51 request.setAttribute("totalCount", totalCount); 52 request.setAttribute("categorylist", categorylist); 53 request.setAttribute("newsList", newsList); 54 55 request.getRequestDispatcher("/jsp/admin/newsDetailList.jsp").forward(request, response); 56 } 57 58 @Override 59 protected void doPost(HttpServletRequest req, HttpServletResponse resp) 60 throws ServletException, IOException { 61 doGet(req, resp); 62 } 63 64 @Override 65 protected void service(HttpServletRequest arg0, HttpServletResponse arg1) 66 throws ServletException, IOException { 67 super.service(arg0, arg1); 68 } 69 70 }
web.xml配置:
1 <!--模糊查询多条件 --> 2 <servlet> 3 <servlet-name>newsListByLikeServlet</servlet-name> 4 <servlet-class>com.cn.pb.servlet.NewsListByLike2</servlet-class> 5 </servlet> 6 <servlet-mapping> 7 <servlet-name>newsListByLikeServlet</servlet-name> 8 <url-pattern>/servlet/newsListByLikeServlet</url-pattern> 9 </servlet-mapping>
这里的流程我要说一下,servlet为什么写在doGet方法中,是get请求而不是Post请求:因为页面走向是这样的用户请求访问:
1、http://localhost:8080/news/servlet/newsListByLikeServlet进来的是这个列表页,
2、请求这个servlet会映射到朝NewsListByLike2.java,
3、然后这个servlet中把页面中需要的各个对象和变量取到再传给newsDetailList.jsp页面
4、模糊查询的form提交的action也是到NewsListByLike2.java这个servlet中去的,查出的结果也还是要在newsDetailList.jsp页面显示,所以与第3步一致
5、那为什么form提交的是post,而一般页面查询请求是get,上面我的servlet写在doGet方法中了,但要注意,我的doPost方法中调用了doGet方法,也就是说一进来查询条件(分类和关键字)用户没有输入的都为空的,这时候我还是要出全列表数据的,这时候是Get操作,当我用户选择分类和关键字点GO的时候,form表单进行了Post提交,还是提交给我的这个servlet处理,这时候走doPost,但实际上方法里还是可以执行的我doGet里的代码,代码可以复用的。
准备写一篇分离分页,把分页封装到一个类中的实例