jsp页面数据从数据库加载
web页面动态加载、这也就是前后端数据交互的一种方式
利用Dao数据库控制类连接数据库,用sql语句获取数据库数据
Goods是商品类,从数据库获取数据赋值给Goods类对象
Conns是连接数据库的类,如何连接数据库
public class GoodsDao {
public Connection con = new Conns().getConnection();
public ArrayList<Goods> getGoodsList() {
ArrayList<Goods> list = new ArrayList<Goods>();
String sql1 = "select * from goos_detail";
try {
if (con == null) {
con = new Conns().getConnection();
}
PreparedStatement pst = con.prepareStatement(sql1);
ResultSet executeQuery = pst.executeQuery();
while (executeQuery.next()) {
Goods pl = new Goods();
pl.setId(executeQuery.getInt("goodsid"));
pl.setPic(executeQuery.getString("main_img"));
pl.setPrice(executeQuery.getString("price"));
pl.setName(executeQuery.getString("name"));
pl.setType(executeQuery.getString("type"));
// pl.setTime(executeQuery.getString("上架时间"));
pl.setTotal(executeQuery.getString("num"));
list.add(pl);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
Conns.close(con);
}
return list;
}
}
jsp可以直接导入Java类,在<%%>中调用Java类中的方法获取到数据库数据集合
在head前导入对应的Java类
<%@page import=“javabeen.Goods”%>
<%@page import=“java.util.ArrayList”%>
<%@page import=“javabeen.GoodsDao”%>
GoodsDao dao =new GoodsDao();
ArrayList<Goods> goodslist= dao.getGoodsList();
jsp页面通过out.write()将页面转换成动态加载
for (int i = 0; i < 9; i++) {
Goods gs = goodslist.get(i);
out.write("<div class='on'>");
out.write("<img src= '"+gs.getPic() +"' style=' margin-top:auto; margin-left:10px;' /><br />");
out.write("<br /> <a href='Untitled-1.jsp?id="+gs.getId() +"'>"+gs.getName() +"</a><br /> <br />");
out.write("<div class='onon'>¥"+gs.getPrice() +"</div>");
out.write("</div>");
}