基于Javaweb的小项目

基于Javaweb的小项目,第1张

1.IOC容器对applicationContent.xml文件里的配置进行读取并解析
  • 对代码中的DAO层、service层、controller层及其相互之间的关系进行配置
  • 【applicationContent.xml】


DOCTYPE beans[
        <!ELEMENT beans (bean*)>
        <!ELEMENT bean (property*)>
        <!ELEMENT property (#PCDATA)>

        <!ATTLIST bean id ID #REQUIRED>
        <!ATTLIST bean class CDATA #IMPLIED>

        <!ATTLIST property name CDATA #IMPLIED>
        <!ATTLIST property ref IDREF #IMPLIED>
 ]>

<beans>
    
    <bean id="userBasicDAO" class="com.javaweb.qqzone.zone.dao.impl.UserBasicDAOImpl" />
    <bean id="topicDAO" class="com.javaweb.qqzone.zone.dao.impl.TopicDAOImpl"/>
    <bean id="replyDAO" class="com.javaweb.qqzone.zone.dao.impl.ReplyDAOImpl"/>
    <bean id="hostReplyDAO" class="com.javaweb.qqzone.zone.dao.impl.HostReplyDAOImpl"/>

    
    <bean id="userBasicService" class="com.javaweb.qqzone.zone.service.impl.UserBasicServiceImpl">
        <property name = "userBasicDAO" ref = "userBasicDAO"/>
    bean>

    <bean id="topicService" class="com.javaweb.qqzone.zone.service.impl.TopicServiceImpl">
        <property name = "topicDAO" ref = "topicDAO"/>
        <property name = "replyService" ref = "replyService"/>
        <property name = "userBasicService" ref = "userBasicService"/>
    bean>

    <bean id="replyService" class="com.javaweb.qqzone.zone.service.impl.ReplyServiceImpl">
        <property name="replyDAO" ref="replyDAO"/>
        <property name="hostReplyService" ref="hostReplyService"/>
        <property name = "userBasicService" ref = "userBasicService"/>
    bean>

    <bean id="hostReplyService" class="com.javaweb.qqzone.zone.service.impl.HostReplyServiceImpl">
        <property name="hostReplyDAO" ref="hostReplyDAO"/>
    bean>


    
    <bean id="user" class="com.javaweb.qqzone.zone.controller.UserController">
        <property name = "userBasicService" ref = "userBasicService"/>
        <property name = "topicService" ref = "topicService"/>
    bean>

    <bean id="page" class="com.javaweb.qqzone.zone.controller.PageController"/>
    
    <bean id="topic" class="com.javaweb.qqzone.zone.controller.TopicController">
        <property name = "topicService" ref = "topicService"/>
        <property name = "replyService" ref = "replyService"/>
    bean>

    <bean id="reply" class="com.javaweb.qqzone.zone.controller.ReplyController">
        <property name = "replyService" ref = "replyService"/>
    bean>
beans>
  • 【BeanFactory.java】—— Bean工厂类
package com.javaweb.qqzone.myssm.ioc;

public interface BeanFactory {
    Object getBean(String id);
}

  • applicationContent.xml文件中的参数进行读取,并组装各层之间的依赖关系
  • 【ClassPathXmlApplicationContext.java】
package com.javaweb.qqzone.myssm.ioc;

import com.javaweb.qqzone.myssm.util.StringUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class ClassPathXmlApplicationContext implements BeanFactory{

    private Map<String, Object> beanMap = new HashMap<>();
    private String path = "applicationContext.xml";

    public ClassPathXmlApplicationContext(){
        this("applicationContext.xml");
    }

    public ClassPathXmlApplicationContext(String path) {
        if (StringUtil.isEmpty(path)) {
            throw new RuntimeException("IOC容器的配置文件没有指定....");
        }

        try {
            InputStream inputStream = getClass().getClassLoader().getResourceAsStream(path);
            //1.创建DocumentBuilderFactory对象
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            //2.创建DocumentBuilder对象
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            //3.创建Document对象
            Document document = documentBuilder.parse(inputStream);
            //4.获取所有的bean节点
            NodeList beanNodeList = document.getElementsByTagName("bean");

            for (int i = 0; i < beanNodeList.getLength(); i++) {
                Node beanNode = beanNodeList.item(i);
                if (beanNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element beanElement = (Element) beanNode;
                    String beanId = beanElement.getAttribute("id");
                    String className = beanElement.getAttribute("class");

                    Class beanClass = Class.forName(className);
                    //创建bean实例
                    Object beanObj = beanClass.newInstance();
                    //将bean实例对象保存到map容器中
                    beanMap.put(beanId, beanObj);

                    //到目前为止,此处需要注意的是:bean和bean之间的依赖关系还没有设置
                }
            }

            //5.组装bean之间的依赖关系
            for (int i = 0; i < beanNodeList.getLength(); i++) {
                Node beanNode = beanNodeList.item(i);
                if (beanNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element beanElement = (Element) beanNode;
                    String beanId = beanElement.getAttribute("id");
                    NodeList beanChildNodeList = beanElement.getChildNodes();
                    //System.out.println("length:"+beanChildNodeList.getLength());
                    for (int j = 0; j < beanChildNodeList.getLength(); j++) {
                        Node beanChildNode = beanChildNodeList.item(j);
                        if (beanChildNode.getNodeType() == Node.ELEMENT_NODE && "property".equals(beanChildNode.getNodeName())){
                            Element propertyElement = (Element) beanChildNode;
                            String propertyName = propertyElement.getAttribute("name");
                            String propertyRef = propertyElement.getAttribute("ref");

                            //1)找到property对应的实例
                            Object refObj = beanMap.get(propertyRef);
                            //2)将refObj设置到当前bean对应的实例的property属性上去
                            Object beanObj = beanMap.get(beanId);
                            Class beanClazz = beanObj.getClass();
                            Field propertyField = beanClazz.getDeclaredField(propertyName);
                            propertyField.setAccessible(true);
                            propertyField.set(beanObj, refObj);
                        }
                    }
                }
            }


        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Object getBean(String id) {
        return beanMap.get(id);
    }
}


2.业务处理

主要负责业务的开启,提交,回滚阶段

  • 【TransactionManager.java】
package com.javaweb.qqzone.myssm.transaction;


import com.javaweb.qqzone.myssm.util.ConnectionUtil;
import java.sql.Connection;
import java.sql.SQLException;

public class TransactionManager {
    //开启事务
    public static void beginTrans() throws SQLException {

        ConnectionUtil.getConnection().setAutoCommit(false);
    }

    //提交事务
    public static void commit() throws SQLException {

        Connection conn = ConnectionUtil.getConnection();
        conn.commit();
        ConnectionUtil.closeConnection();
    }

    //回滚事务
    public static void rollback() throws SQLException {

        Connection conn = ConnectionUtil.getConnection();
        conn.rollback();
        ConnectionUtil.closeConnection();
    }
}

3.监听器——监听上下文启动

监听上下文启动,在上下文启动时去创建IOC容器,然后将其保存到application作用域
后面中央控制器再从application作用域中去获取IOC容器

  • 【ContextLoaderListener.java】
package com.javaweb.qqzone.myssm.listeners;

import com.javaweb.qqzone.myssm.ioc.BeanFactory;
import com.javaweb.qqzone.myssm.ioc.ClassPathXmlApplicationContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

//监听上下文启动,在上下文启动时去创建IOC容器,然后将其保存到application作用域
//后面中央控制器再从application作用域中去获取IOC容器
@WebListener
public class ContextLoaderListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        //1.获取ServletContext对象
        ServletContext application = servletContextEvent.getServletContext();
        //2.获取上下文的初始化参数
        String path = application.getInitParameter("contextConfigLocation");
        //3.创建IOC容器
        BeanFactory beanFactory = new ClassPathXmlApplicationContext(path);
        //4.将IOC容器保存到application作用域中
        application.setAttribute("beanFactory", beanFactory);
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}
4.字符串工具类
  • 【StringUtil.java】
package com.javaweb.qqzone.myssm.util;

public class StringUtil {
    //判断字符串是否为空或者null
    public static boolean isEmpty(String str) {
        return str==null || "".equals(str);
    }

    public static boolean isNotEmpty(String str) {
        return !isEmpty(str);
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/794884.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-06
下一篇 2022-05-06

发表评论

登录后才能评论

评论列表(0条)

保存