1.功能介紹
前面我們實現了商品所有信息的顯示,接下來要實現某一商品詳細信息的顯示。那麼我們就要思考了,我們如何通過頁面跳轉將我們對應的商品傳遞到下一個頁面。其實在前面寫index.jsp主頁面的時候,用戶點擊對應的商品會跳轉到details.jsp這個頁面,我們可以在這裏的<a>標籤中將我們商品的id傳進去:
<a href="details.jsp?id=<%=good.getId() %>" class="prod_details">詳情</a>
這樣我們就可以顯示該條商品的詳細信息了。
ok,商品的id有了,接下來我們就是根據id從數據庫中獲取該商品的信息。
2.獲取單條數據
和前面一樣,對數據庫的操作,我們使用GoodDao這個類實現,接下來是獲取單條記錄的詳細實現:
//根據商品的id獲取數據
public Good getGoodById(int id){
Connection conn=null;
PreparedStatement prep=null;
ResultSet rs=null;
Good good=new Good();
try {
conn=DBHelper.getConnection();
String sql="select * from good where id=?";
prep=(PreparedStatement) conn.prepareStatement(sql);
prep.setInt(1, id);
rs=prep.executeQuery();
if(rs.next())
{
good.setId(rs.getInt("id"));
good.setName(rs.getString("name"));
good.setPrice(rs.getDouble("price"));
good.setInfor(rs.getString("infor"));
good.setImage(rs.getString("image"));
}
return good;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
3.詳細頁面的實現
ok,這樣我們就可以通過這個方法獲取一條記錄,接下來我們要做的就是將數據顯示出來。仍然和前面一樣,我們的details.jsp頁面很多,現貼出關鍵代碼:
<!-- 找到你啦,我們要用的東西在這裏 -->
<div class="center_content">
<%
//根據地址裏面的id參數,獲取到數據庫中的商品
GoodDao dao=new GoodDao();
Good good=new Good();
good=dao.getGoodById(Integer.parseInt(request.getParameter("id")));
%>
<!-- 商品詳細信息處 -->
<div class="center_title_bar"><%=good.getName() %></div>
<div class="prod_box_big">
<div class="top_prod_box_big"></div>
<div class="center_prod_box_big">
<div class="product_img_big">
<a href="javascript:popImage('images/big_pic.jpg','Some Title')" title="header=[Zoom] body=[ ] fade=[on]"><img src="images/<%=good.getImage() %>" alt="" title="" border="0" /></a>
</div>
<div class="details_big_box">
<div class="product_title_big"><%=good.getName() %></div>
<div class="specifications">
介紹: <span class="blue"><%=good.getInfor() %></span><br />
</div>
<div class="prod_price_big"><span class="price">價格:<%=good.getPrice() %></span></div>
<a href="#" class="addtocart">加入購物車</a>
</div>
</div>
<div class="bottom_prod_box_big"></div>
</div>
</div>
4.頁面效果
好啦,功能和頁面都寫好了,我們來看一看點擊商品“大哥大”的效果:
這裏1處是我們商品的詳細信息,通過2處我們可以發現,頁面跳轉的時候傳過來的id=5,<a>傳遞參數是get方式傳遞的。
好,這兩個頁面的功能都實現了,接下來要進入到本工程我們關鍵的地方了:使用cookie顯示最近瀏覽商品的前5條信息。