完成商品列表的展示----Java EE三层架构(web+service+dao)

三层架构主要体现三目录结构:

image.png

ProductListServlet.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 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 findAllProduct() throws SQLException {
        // 没有复杂业务
        //传递请求到dao层
        ProductDao dao = new ProductDao();
        List 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 findAllProduct() throws SQLException {
        // 操作数据库
        QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "select * from product";
        List productList = runner.query(sql, new BeanListHandler(Product.class));
        return productList;
    }
    
}

JSP页面展示:以EL表达式与JSTL配合使用

    
        

${product.pname }

商城价:¥${product.shop_price }

你可能感兴趣的:(完成商品列表的展示----Java EE三层架构(web+service+dao))