-2
私は、読み込み中に最初のカテゴリをロードする必要があり、製品と私はlistCategoriesとgetProducts関数でデータベース接続クラスを持っているjspページを持っていると仮定してください私の質問は接続して閉じるまたは呼び出されたすべての関数で時のDB接続は、JSPページと近いページがロードされたサンプルコードの上にDBへの接続:ベストプラクティスデータベース接続とクローズ
public class DbConnection {
private Connection conn = null;
private PreparedStatement ps = null;
private ResultSet rs = null;
private void connect() {
try {
DriverManager.registerDriver(new Driver());
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/shop", "", "");
} catch (SQLException ex) {
Logger.getLogger(DbConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void close() {
try {
if (!conn.isClosed()) {
conn.close();
}
} catch (SQLException ex) {
Logger.getLogger(DbConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
public List<Category> listCategories() {
connect();
List<Category> listCategory = new ArrayList<>();
try {
ps = conn.prepareStatement("select * from Category where sub_category=0");
rs = ps.executeQuery();
while (rs.next()) {
Category u = new Category(rs.getInt("id"), rs.getString("name"), rs.getInt("sub_category"));
listCategory.add(u);
}
return listCategory;
} catch (SQLException ex) {
Logger.getLogger(DbConnection.class.getName()).log(Level.SEVERE, null, ex);
}finally{
close();
}
return null;
}
public List<Products> getProducts() {
connect();
List<Products> listProducts = new ArrayList<>();
try {
ps = conn.prepareStatement("select * from products");
rs = ps.executeQuery();
while (rs.next()) {
Products p = new Products(rs.getInt("id"), rs.getString("name"));
listCategory.add(p);
}
return listCategory;
} catch (SQLException ex) {
Logger.getLogger(DbConnection.class.getName()).log(Level.SEVERE, null, ex);
}finally{
close();
}
return null;
}
}
とサンプルのJSPコード:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<%for(Category c: dc.listCategories()){%>
<h1><%=c.getName()%></h1>
<%}%>
<%for(Products p: dc.getProducts()){%>
<h1><%=p.getName()%></h1>
<%}%>
<body>
<h1>Hello World!</h1>
</body>
</html>
ベストプラクティスでは、スクリプトレットを使用したり、ロジックとプレゼンテーションの問題を分けるSpring MVCのようなフレームワークを使用しないことをお勧めします。 – chrylis
私は議論の余地がないので、建設的ではないので、この質問を締めくくっています。 – EJoshuaS
接続プールを使用してDBCP2などの接続を管理する必要があります – 11thdimension