2015-04-03 74 views
0

我正在創建一個電子商務項目作爲我學習的一部分。我想在同一個JSP頁面上顯示一個類別中的所有產品。例如,如果用戶點擊「筆記本」類別,則必須顯示該類別中可用的所有產品。所有類別的所有產品都放在一張大桌子上。使用主鍵在jsp中顯示來自mysql數據庫的所有數據

我的數據庫方案是:

create table products(product_id varchar(20), 
product_name varchar(20), 
product_prize varchar(20), 
product_category varchar(20), 
primary key(product_id)); 

我的主鍵是product_id。但是,我目前的實現需要單獨的JSP頁面爲每個人product_id。當我有很多產品時,這是不切實際的。

類別頁面的一個例子,lapcategory.jsp

<% int sec1=1; 
    int sec2=2; 
    int sec3=3; 
    int sec4=4; 
    int sec5=5; 
    int sec6=6; 
%> 

<td> 
    <center> 
    <%if (sec1 ==1){ %> 
    <jsp:include page="includesPage/_sec1.jsp"></jsp:include> 
    <% } %> 
    </center> 
</td> 

<td> 
    <center> 
    <%if (sec2 ==2){ %> 
    <jsp:include page="includesPage/_sec2.jsp"></jsp:include> 
    <% } %> 
    </center> 
</td> 

此鏈接到各個欄目頁面。然後,我也有章節頁面,_sec1.jsp,_sec2.jsp等,我在那裏使用product_id獲取數據。例如,_sec1.jsp

String idn="20"; 

DB_Conn con = new DB_Conn(); 
Connection c = con.getConnection(); 
Statement statement = c.createStatement() ; 
ResultSet resultset = statement.executeQuery("select product_id,product_name,product_desc,product_prize from product where product_id="+idn); 

while(resultset.next()){ 

    String product_id = resultset.getString(1); 
    String product_name = resultset.getString(2); 
    String product_desc = resultset.getString(3); 
    String product_prize = resultset.getString(4); 
    %> 

    <div id="se1"> 
    <a href="product.jsp?id=<%=product_id%>"><% out.println(product_name); %></a><br> 
    <a href="#">Rs.<% out.println(product_prize); %></a> 

<% 
} %> 

</div> 

基本上,我要創建爲每個產品ID,這顯然不是一件容易的事處理個別的內頁。我的問題是,做這件事的正確方法是什麼?使用ArrayList的東西,也許?

回答

0

我理解你的問題,但我會建議,而不是寫在jsp中的數據庫查詢相關的代碼創建一個DAO,查詢數據庫,然後在一個數據對象中設置結果,數據對象將包含所有您需要的屬性在JSP中顯示。在從數據庫讀取數據對象的同時設置這個數據對象中的值,然後將該數據對象放在一個數組列表中,並將該數組列表填充到Jsp中。通過這種方式,您可以在一個jsp的幫助下顯示所有產品,並且不需要創建單獨的jsp。

相關問題