简体   繁体   中英

Display all data from mysql database in a jsp using primary key

I am creating an e-commerce project as part of my studies. I want to display all products in a category on same JSP page. For example, if the user clicks the "Laptop" category, I have to display all products available in that category. All products for all categories are together in one large table.

My database scheme is:

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

My primary key is product_id . However, my current implementation needs separate JSP pages for each individual product_id . This isn't going to be practical when I have many products.

An example of a category page, 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>

This links to individual section pages. Then, I also have the section pages, _sec1.jsp , _sec2.jsp , etc. and I fetch data there using product_id . For example, _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>

Basically, I have to create individual inner pages for each product ID, which obviously isn't going to be easy to deal with. My question is, what is the proper way to do this? Something using ArrayList , maybe?

I understand your problem but i will suggest that instead of writing database query related code in jsp create one DAO , query the db and then set the result in one data object , data object will contain all the attributes that you need to display in JSP . Set the values in this Data object while reading it from db , then put that dataObject in one arrayList and populate that arrayList in Jsp's . in this way you can display all the products with the help of one jsp and there is no need to create separate jsp's .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM