发表于: 2017-10-13 22:51:18

1 692


今天完成的事情

了解分页的相关知识,并尝试实现

网页的排列方式一般有两种,一种是一个页面能把所有内容显示完,还有一种是不能再一个页面中显示全部内容时,就要用分页来显示。

分页是将所有数据分段展示给用户的技术,用户看到的只是全部数据的其中一部分,用户可以通过页码或是翻页来进行跳转,知道找到自己想看到的内容。

可以进行分页处理的地方有:1客户端,2服务器,3数据库端。在客户端进行分页,需要进行传输的数据量很大,必然加大服务器的负载。在服务器端进行分页,大部分数据还是会被传输到服务器端。

所以,比较好的分页做法应该是每次翻页的时候只从数据库里检索相应页面大小的数据。

利用sql语句:selct * from table_name order by id desc limit ?,?  将其写入dao中,命令为list方法,之后可以进行调用。

首先定义页面显示数量,int start=0;int count=5;将start和count作为参数传入之前的sql语句中,就可以实现在页面中显示5条数据。

根据页面提交的start,更新start的值,定义int next=start+count,然后把next传递给jsp文件,在jsp中增加超链<a herf="?start=${next}">[下一页]</a>,将next的值传递给start。

定义int pre=start=count,然后将pre传给jsp,在jsp中增加超链<a herf="?start=${pre}">[上一页]</a>,将pre的值传给start。

这样,当点击相应的超链时,相应的start值传入控制器,然后执行sql语句,就可以查询出相应的记录,并显示出来。

其主要代码如下:

public class HeroListServlet extends HttpServlet {
protected void service(HttpServletRequest request,
                          HttpServletResponse response)
throws ServletException,IOException{

int start=0;
       int count=5;     //定义每一页显示的记录条数

       try{
start=Integer.parseInt(request.getParameter("start"));
       }catch (NumberFormatException e){

}
int next=start+count;      //下一页,用获取的参数start+count计算next,然后把next传递给jsp
       int pre=start-count;      //上一页,
       int total=new HeroDAO().getTotal();
       int last;               //最后一页,需要根据总数total和每页条数count计算得出,

       if(0==total%count) //如果total能被count整除,
           last = total-count;
       else                          //如果total不能被count整除,
           last=total-total%count;

       pre=pre<0?0:pre;               //边界处理
       next=next>last?last:next;

       request.setAttribute("next",next);
       request.setAttribute("pre",pre);
       request.setAttribute("last",last);

       List<Hero> heros=new HeroDAO().list(start,count);


       request.setAttribute("heros",heros);
       request.getRequestDispatcher("listHero.jsp").forward(request,response);

执行结果:

明天的计划

学习ssm框架,并尝试加以实现


遇到的问题

进度缓慢


收获

了解了怎么分页,以及jsp中怎么加入超链。




返回列表 返回列表
评论

    分享到