三层架构主要体现三目录结构:
image.pngProductListServlet.java文件代码:
package com.zys.web;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import com.zys.domain.Product;
import com.zys.service.ProductService;
import com.zys.utils.DataSourceUtils;
public class ProductListServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//传递请求到service层
ProductService service = new ProductService();
List<Product> productList = null;
try {
productList = service.findAllProduct();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//全部的商品的数据准备好了 转发给jsp进行数据的展示
request.setAttribute("productList", productList);
request.getRequestDispatcher("/product_list.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
ProductService.java文件代码:
package com.zys.service;
import java.sql.SQLException;
import java.util.List;
import com.zys.dao.ProductDao;
import com.zys.domain.Product;
public class ProductService {
public List<Product> findAllProduct() throws SQLException {
// 没有复杂业务
//传递请求到dao层
ProductDao dao = new ProductDao();
List<Product> productList = dao.findAllProduct();
return productList;
}
}
ProductDao.java文件代码:
package com.zys.dao;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import com.zys.domain.Product;
import com.zys.utils.DataSourceUtils;
public class ProductDao {
public List<Product> findAllProduct() throws SQLException {
// 操作数据库
QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "select * from product";
List<Product> productList = runner.query(sql, new BeanListHandler<Product>(Product.class));
return productList;
}
}
JSP页面展示:以EL表达式与JSTL配合使用
<c:forEach items="${productList }" var="product">
<div class="col-md-2" style="height:250px">
<a href="productInfo?id=${product.pid }">
<img src="${pageContext.request.contextPath }/${product.pimage }" width="170" height="170" style="display: inline-block;">
</a>
<p>
<a href="product_info.html" style='color: green'>${product.pname }</a>
</p>
<p>
<font color="#FF0000">商城价:¥${product.shop_price }</font>
</p>
</div>
</c:forEach>
网友评论