jsp部分:
<%
int onepage=4;//每页四个商品
int goodsSum=shopdao.selectSum();//商品总数
int Total_page = (goodsSum+onepage-1)/onepage;//计算总页数
String now= request.getParameter("now_page");//获取当前页
int now_p = 1;//设置当前页为1
if(now==null){//给当前页赋值
now_p=1;//页面第一次加载时,给当前页赋值为第一页
}else{
//给当前页赋值为目标页
now_p=Integer.parseInt(now);
if(now_p<1){//当得到now_page小于一时(即第一页往上翻页情况)使now_page为1
now_p=1;
}else if(now_p>Total_page){//当now_page大于总页数时(即最后一页往下翻页) now_page为最后一页
now_p=Total_page;
}
}
list = shopdao.selectGoods((now_p*onepage)-onepage,onepage);//调用方法分页显示商品
for(int i =0;i<list.size();i++){ %>
<div id="box_shop_one">
<div id="box_shop_one1">
<div id="box_shop_oneimage"><img src="<%=list.get(i).getImage() %>"></div>
<div id="box_shop_oneprice"><%=list.get(i).getPrice() %></div>
<div id="box_shop_onename"><%=list.get(i).getName() %></div>
<div id = "box_shop_onetype">
<span><%=list.get(i).getType() %></span>条评价
</div>
<div id = "box_shop_owner"><a href="#">京东自营旗舰店</a></div>
<div id="box_shop_icon"></div>
<div id="box_shop_tips"></div>
<div id="box_shop_compare">
<a href="#">□ 对比</a>
</div>
<div id="box_shop_foucs">
<a href="#">❤ 关注</a>
</div>
<div id="box_shop_addcart">
<img alt="" src="../image/buy.png">
<a href="doshop.jsp?id=<%=list.get(i).getId() %>" target="_Blank"> 加入购物车</a>
</div>
</div>
</div>
<%} %>
</div>
<div id="box_4">
<ul id="pagination-digg">
<li class="previous-off"><a href="#">共计 <%=Total_page %> 页</a>
<li class="previous-off"><a href="shop.jsp?now_page=<%=now_p-1%>"><上一页</a></li>
<li class="previous-off"><a href="#">当前 <%=now_p %> 页</a>
<li class="next"><a href="shop.jsp?now_page=<%=now_p+1%>">下一页 ></a></li>
</ul>
</div>
dao包部分:
public List<Goods> selectGoods(int start,int num){
/**
* 分页查询
* **/
List<Goods> list = new ArrayList<Goods>();
Connection con =null;
PreparedStatement pst = null;
ResultSet rs = null;
try {
con = SingleTest.getST().getCon();
String sql = "select * from goods limit ?,?";
pst=con.prepareStatement(sql);
pst.setInt(1, start);
pst.setInt(2, num);
rs = pst.executeQuery();
while(rs.next()){
Goods goods = new Goods();
goods.setId(rs.getInt("ID"));
goods.setImage(rs.getString("image"));
goods.setName(rs.getString("name"));
goods.setPrice(rs.getDouble("price"));
goods.setType(rs.getString("type"));
list.add(goods);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
SingleTest.getST().closeAll(rs,pst, con);;
}
return list;
}
public int selectSum(){
/**
* 查询数量
* **/
Connection con =null;
PreparedStatement pst = null;
ResultSet rs = null;
int i = 0;
try {
con = SingleTest.getST().getCon();
String sql = "select * from goods";
pst=con.prepareStatement(sql);
rs = pst.executeQuery();
while(rs.next()){
i++;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
SingleTest.getST().closeAll(rs,pst, con);;
}
return i;
}