案例40-层与层之间的解耦(面向接口编程)

Posted jepson6669

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了案例40-层与层之间的解耦(面向接口编程)相关的知识,希望对你有一定的参考价值。

1 bean.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans>
    <!-- 配置AdminServiceImpl的清单 -->
    <bean id="adminService" class="www.test.service.impl.AdminServiceImpl"></bean>
</beans>

2 BeanFactory工厂类代码

package www.test.utils;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class BeanFactory {

    public static Object getBean(String id){
        //生成对象--根据清单生产--配置文件--将每一个bean对象的生产细节配置到配置文件中
        
        //使用dom4j的xml解析技术 导入两个jar包
        // dom4j-1.6.1.jar 和 jaxen-1.1-beta-6.jar
        
        try {
            // 1 创建解析器
            SAXReader reader = new SAXReader();
            // 2 解析文档--bean.xml 在src下面
            String path = BeanFactory.class.getClassLoader().getResource("bean.xml").getPath();
          //读取
            Document doc = reader.read(path);
            
            // 3 获得元素--参数是xpath规则
            Element element = (Element) doc.selectSingleNode("//bean[@id=‘"+id+"‘]");
            //<bean id="adminService" class="www.test.service.impl.AdminServiceImpl"></bean>
            String className = element.attributeValue("class"); 
            //www.test.service.impl.AdminServiceImpl
            
            //使用反射创建对象
            Class clazz = Class.forName(className);
            Object object = clazz.getDeclaredConstructor().newInstance();
            
            return object;
            
        } catch (Exception e) {
            
            e.printStackTrace();
        }
        
        return null;
    }
}

3 AdminService接口代码

package www.test.service;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import www.test.dao.AdminDao;
import www.test.domain.Category;
import www.test.domain.Order;
import www.test.domain.Product;

public interface AdminService {

    // 获取分类
    public List<Category> findAllCategory();

    // 添加商品
    public void saveProduct(Product product) throws SQLException;

    // 获取商品列表
    public List<Product> findProductList() throws SQLException ;
    public void deleteProductByPid(String pid) throws SQLException;

    // 商品修改的回显
    public Map<String, Object> productBackShow(String pid) throws SQLException;

    // 获取所有订单
    public List<Order> findAllOrdersList() throws SQLException;

    //查询订单详情
    public List<Map<String, Object>> findOrderInfoByOid(String oid) throws SQLException;

}

4 AdminServiceImpl接口实现类代码

package www.test.service.impl;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import www.test.dao.AdminDao;
import www.test.domain.Category;
import www.test.domain.Order;
import www.test.domain.Product;
import www.test.service.AdminService;

public class AdminServiceImpl implements AdminService {

    // 获取分类
    public List<Category> findAllCategory() {
        AdminDao dao = new AdminDao();
        try {
            return dao.findAllCategory();
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    // 添加商品
    public void saveProduct(Product product) throws SQLException {
        AdminDao dao = new AdminDao();
        dao.saveProduct(product);
    }

    // 获取商品列表
    public List<Product> findProductList() throws SQLException {
        AdminDao dao = new AdminDao();
        return dao.findProductList();
    }

    public void deleteProductByPid(String pid) throws SQLException {
        AdminDao dao = new AdminDao();
        dao.deleteProductByPid(pid);
    }

    // 商品修改的回显
    public Map<String, Object> productBackShow(String pid) throws SQLException {
        AdminDao dao = new AdminDao();
        return dao.productBackShow(pid);
    }

    // 获取所有订单
    public List<Order> findAllOrdersList() throws SQLException {
        AdminDao dao = new AdminDao();
        return  dao.findAllOrdersList();
        
    }

    //查询订单详情
    public List<Map<String, Object>> findOrderInfoByOid(String oid) throws SQLException {
        
        AdminDao dao = new AdminDao();
        return dao.findOrderInfoByOid(oid);
    }

}

5 AdminServlet代码

package www.test.web.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import com.google.gson.Gson;

import www.test.domain.Category;
import www.test.domain.Order;
import www.test.domain.Product;
import www.test.service.AdminService;
import www.test.service.impl.AdminServiceImpl;
import www.test.utils.BeanFactory;

public class AdminServlet extends BaseServlet{

    // 1 页面加载完毕后异步获得分类数据
    public void findAllCategory(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //提供一个List<Category>转成json字符串
        AdminService service = (AdminService) BeanFactory.getBean("adminService");
        List<Category> categoryList = service.findAllCategory();
        
        //将List<Category>转换成json格式
        Gson gson = new Gson();
        String json = gson.toJson(categoryList);
        
        //解决乱码并写出
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(json);
        
    }
    
    
    // 2 商品列表的展示findAllProductList
    public void findAllProductList(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        AdminService service = (AdminService) BeanFactory.getBean("adminService");
        List<Product> productList = null;
        try {
            productList = service.findProductList();
        } catch (SQLException e) {
            
            e.printStackTrace();
        }
        
        // 转发
        request.setAttribute("productList", productList);
        request.getRequestDispatcher("/admin/product/list.jsp").forward(request, response);
        
    }
    
    // 3 删除商品 delProduct
    public void delProduct(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        //获取要删除商品的id
        String pid = request.getParameter("pid");
        AdminService service = (AdminService) BeanFactory.getBean("adminService");
        try {
            service.deleteProductByPid(pid);
            //删除成功后回到商品列表页面
            List<Product> productList = service.findProductList();
            request.setAttribute("productList", productList);
            request.getRequestDispatcher("/admin/product/list.jsp").forward(request, response);
        } catch (SQLException e) {
            
            e.printStackTrace();
        }
        
    }
    
    // 4 修改商品的操作 editProduct
    public void editProduct(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        //修改商品的回显部分
        
        AdminService service = (AdminService) BeanFactory.getBean("adminService");
        // 1获取要修改的商品的pid
        String pid = request.getParameter("pid");
        // 2 调用AdminService的方法
        Map<String, Object> map = null;
        Product product =new Product();
        try {
            map = service.productBackShow(pid);
            /*{shop_price=2298.0, market_price=2399.0, 
            pflag=0, pimage=products/1/c_0014.jpg, 
            pname=vivo X5Pro, is_hot=1, 
            pdesc=移动联通双4G手机 3G运存版 极光白【购机送蓝牙耳机+蓝牙自拍杆】
            新升级3G运行内存·双2.5D弧面玻璃·眼球识别技术,
             pid=11, cid=1, pdate=2015-11-02}*/
            
            // 将除了category的进行自动映射封装
            BeanUtils.populate(product, map);
            
            //private Category category; 进行手动封装
            Category category = new Category();
            String cid =map.get("cid").toString();
            category.setCid(cid);
            
            //将category封装到product中
            product.setCategory(category);
            
        } catch (Exception e) {
            
            e.printStackTrace();
        }
        //存储转发
        request.setAttribute("product", product);
        request.getRequestDispatcher("/admin/product/edit.jsp").forward(request, response);
        
    }
    
    
    // 5 获得所有订单 findAllOrders
    public void findAllOrders(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 获得所有的订单信息---List<Order>
        AdminService service = (AdminService) BeanFactory.getBean("adminService");
        List<Order> orderList = null;
        try {
            orderList = service.findAllOrdersList();
        } catch (SQLException e) {
            
            e.printStackTrace();
        }
        
        request.setAttribute("orderList", orderList);
        request.getRequestDispatcher("/admin/order/list.jsp").forward(request, response);
    }
    
    
    // 6根据订单oid查询订单项和商品信息 findOrderInfoByOid
    public void findOrderInfoByOid(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        //模拟从服务器读数据有一个延迟的效果
        try {
            Thread.sleep(500);
        } catch (InterruptedException e1) {
            
            e1.printStackTrace();
        }
        
        //获得oid
        String oid = request.getParameter("oid");
        
        //用解耦合的方式进行编码-----解web层与service层
        //使用工厂+反射+配置文件
        AdminService service = (AdminService) BeanFactory.getBean("adminService");
        
        
        List<Map<String,Object>> mapList = null;
        try {
            mapList = service.findOrderInfoByOid(oid);
        } catch (SQLException e) {
            
            e.printStackTrace();
        }
        //格式转换
        Gson gson = new Gson();
        String json = gson.toJson(mapList);
        //注意ajax提交回写
        System.out.println(json);
        /*
         * [
         * {"shop_price":5999.0,"count":2,"pname":"微星(MSI)GE62 2QC-264XCN","pimage":"products/1/c_0042.jpg","subtotal":11998.0},
         * {"shop_price":1299.0,"count":1,"pname":"小米 4c 标准版","pimage":"products/1/c_0001.jpg","subtotal":1299.0},{"shop_price":2699.0,"count":6,"pname":"中兴 AXON","pimage":"products/1/c_0002.jpg","subtotal":16194.0},
         * {"shop_price":2298.0,"count":1,"pname":"vivo X5Pro","pimage":"products/1/c_0014.jpg","subtotal":2298.0}]
         */
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(json);
    }
    
}

 

以上是关于案例40-层与层之间的解耦(面向接口编程)的主要内容,如果未能解决你的问题,请参考以下文章

耦合和解耦--工厂单例解耦

spring学习

三分钟带你搞懂Spring解耦和IOC

简单使用Moq框架

java:面向接口编程(解耦)

源码解读Dubbo分层设计思想