Struts+HIbernate+Spring

1.Struts

        取代JSP中的控制功能,为系统添加独立的控制,采用Struts引入标签,实现JSP与后台JAVA代码的分离,JSP只负责显示,与struts.xml配合实现页面跳转

       实现:接收请求,调用业务逻辑组件,返回HTTP响应

        Struts中控制器由底层的一个FilterDispatcher(较老)负责实现,FilterDispatcher类负责接收用户的请求并最终转发用户的请求。

       在web.xml中配置:

      <?xml version="1.0" encoding="ISO-8859-1"?>
      <web-app xmlns="http://java.sun.com/xml/ns/javaee"     XML(标准通用标记语言的子集)命名空间,赋予命名空间一个惟一的名称。不过,很多公司常常会作为指针来使用命名空间指向实际存在的网页,这个网页包含关于命名空间的信息,不同元素可在不同命名控件
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"模式文件提供定义的标签
      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  
     http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"  多个 XML 架构文档提供位置信息
     version="3.0"
     metadata-complete="true">   由部署描述符为Web应用程序提供所有的配置信息

      <filter>
          <filter-name>struts2</filter-name>
          <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
      </filter>

       <filter-mapping>
          <filter-name>struts2</filter-name>
          <url-pattern>/*</url-pattern>
      </filter-mapping>

     在struts.xml中配置:

     <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"   文档声明,在struts-core-2.0.11.2.jar中的struts2.0dtd文件中复制
     "http://struts.apache.org/dtds/struts-2.0.dtd">           源码库
<struts>
    <constant name="struts.objectFactory" value="spring"/>   
    <constant name="struts.devmode" value="true"/>   是否使用开发模式
    <constant name="struts.i18n.encoding" value="GBK"/> 
    <package name="default" extends="struts-default" namespace="/">   包名,要继承的包,命名控件,namespace=“dogs”,则dogs/garfield优先在dogs下找,后去默认命名控件下找

     <action name="information_*" method = "{1}" class="com.web.action.InformationAction">  method = "add"则调用add方法
            <result name="main" type="chain">main</result>
            <result name="list">/informationList.jsp</result>
            <result type="chain">informationList</result>
            <result name="success">/informationList.jsp</result>
            <result name="detail">/informationDetail.jsp</result>
            <result name="input">/addInformation.jsp</result>
            <result name="edit">/editInformation.jsp</result>
       </action>

       </package>

</struts>

      有了Action类(com.web.action.InformationAction),取代在客户端的所有表单提交对象(JSP),Struts.xml根据Action类返回值选择跳转至目的页面,Action类继承ActionSupport类,必须重载 public String execute() throws Exception{}    和  可重载  public void validate(){},当没有指名method默认先执行validate(),execute(),method=“{1}”时,根据name="information_*",调用Action类中的方法*。

是在struts2调用完拦截器栈之后,调用响应Action的execute方法前
详细的说:struts2在接受一个请求之后,会建立相应请求的Action对象,同时生成管理其上下文的ActionContext对象,并将javabean(即Action对象)
的属性放到
Valuestack栈顶,将这些属性初始化,之后struts2会调用拦截器栈中的拦截器(注意这些拦截器会改变valuestack中属性的值,如params拦
截器会完成将表单字段映射
到valuestack属性上。。。),在调用结束后,struts2会将valuestack中的属性映射赋值给Action对象属性,
最后调用action方法。

Action类中的

    public String execute() throws Exception{
           this.Message="Hello, World";

          ActionContext context = ActionContext.getContext();

          Map session = context.getsession();

         session.put("message", message);

         return success;
    }

JSP中,可以使用<%=request.getssion.getAttribute("message").toString%>,也可以使用<s:property value="??.message"/>

<%=request.getssion().getAttribute("message").toString%>使用Struts2.0方式给session存取数据,却用request对象直接访问session对象读取数据

<s:property value="??.message"/>通过Struts2.0的数据绑定机制,传递??.message等同与Action.get??().getMessage();

    package机制用来统一组织和管理Action,你的浏览器地址是根据namespace/action名称 访问的 这个namespace是虚拟路径,可以在项目中完全不存在。随便取但是我在项目中为了方面查找jsp页面,会将jsp文件的路径与namespace想匹配。

    知识点梳理:

           1.使用Action接收用户句表单提交上来的参数

           2.在Action中访问request/session/application对象

           3.package的配置和名称空间的配置,采用累死与JAVA中package的机制统一组织管理Action

           4.Action的配置,包括method属性,动态方法的调用及默认Action配置

           5.Result的配置

    建议:

            1.配置class的默认路径为Project/WebRoot/WEB-INF/classes

            2.web.xml放置在Project/WebRoot/WEB-INF/下

    与JSP区别:

            1.页面跳转使用Action

            2.数据的读取存储使用领域对象(Action对象)

            3.与selevet API 可耦合和解耦合

             解耦合:

                         ActionContext context = ActionContext.getContext();

                         Map request = (Map) context.get("request");

                         Map response = (Map) context.get("response");

                         Map application = (Map) context.getApplication();

                 耦合:

                         HttpServletRequest request = ServletActionContext.getRequest();

                         HttpServletResponse response = ServletActionContext.getResponse();

                         ServletContext application = ServletActionContext.getServletContext();

2.HIbernate  数据库操作

        1.书写类的映射文件

        <?xml version="1.0" encoding="UTF-8"?>
       <!DOCTYPE hibernate-mapping PUBLIC
       "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
       "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">        XML文件格式的验证文件位置,用于检验XML文件格式是否正确
       <hibernate-mapping>
           <class name="com.web.domain.Comment" table="comment">        需要存储的类名,对应的表名
           <id name="id" length="32" column="id" type="java.lang.String">       属性id由hibernate自动生成
               <generator class="uuid.hex">                                          
               </generator>
          </id>
          <property                                                                                            属性
             name="title"
             type="java.lang.String"
             column="title"
             length="64"
             not-null="false"                                                                                 可空
           />。。。

        Hibernate的配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.url">                          数据库地址及数据库名称
            jdbc:mysql://localhost:3306/community
        </property>
        
        <property name="hibernate.connection.driver_class">           数据库驱动类
            com.mysql.jdbc.Driver
        </property>
        
        <property name="hibernate.connection.username">root</property>         访问数据库的用户名及密码
        <property name="hibernate.connection.password">********</property>
    
    <!-- 指定映射文件 -->
    <mapping resource="Chapter04/Apple.hbm.xml"/>
    
    </session-factory>
</hibernate-configuration>

使用Hibernate:

        public static void main(String[] args) {
        Configuration configuration = new Configuration();                         读取hibernate.properties或者hibernate.cfg.xml
        configuration = configuration.configure();
        SessionFactory factory = configuration.buildSessionFactory();       打开与数据库会话,并开始事务
        Session session = factory.openSession();
        Transaction transaction = session.beginTransaction();

       。。。。

        session.save(apple2);

        transaction.commit();       
        session.close();
    }

       查询:session.get(Apple.Class, id);也可以使用HSQL语句:hsql="FROM User WHERE user = 'admin'";  HIbernate.getSessionFactory.getCurrentSession().createQuery(hsql).list();  

当将三个框架一起使用是,无需Hibernate配置文件hibernate.cfg.xml,在applicationContext中配置JAVA BEAN

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost/web"/>
    <property name="username" value="root"/>
    <property name="password" value="chenhaibin"/>
    </bean>

使用时:this.getHibernateTemplate().save(comment);实现保存,也可以使用HSQL实现查询等:String hsql = "from comment where title = '" + title + "'";
        return this.getHibernateTemplate().find(hsql);

  Spring:

        通过XML<bean/>元素能够声明受管POJO,通过设值方法(Setter)和构造器能够完成其依赖对象

        IOC(控制反转):Spring从程序员手中接管实例化对象和注入协作对象(协作bean),控制由程序员手中转移给Spring IOC容器,控制发生了根本性的反转。

       DI(依赖注入):两个或多个对象(UserService,UserDAO)协同工作,其中一个(UserService)需要另一个(UserDAO)协作来完成任务,这种协作通过设置属性的方式来实现(UserService中设置UserDAO属性)。给UserService中的UserDAO属性赋值的过程,成为依赖注入。被注入对象(UserDAO)称为协作bean,接收注入的对象(UserService)被称为依赖bean。

       设置ApplicationContext:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">       本地数据源,可以在任何环境
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost/web"/>
    <property name="username" value="root"/>
    <property name="password" value="chenhaibin"/>
    </bean>

     <bean id="userService" class="com.web.service.imp.UserService">
        <property name="userDAO">
            <ref local="userDAOProxy"/>
        </property>
        <!-- <property name="userDAO">
            <ref local="userDAO"/>
        </property> -->
    </bean>

       实例化:
        String[] files = new String[] {"applicationContext.xml"};
        ApplicationContext context = new ClassPathXmlApplicationContext(files);
        UserService userService = (UserService) context.getBean("userService");
        String ID = userService.getUserIdByName(userName);

原文地址:https://www.cnblogs.com/chengxuyuandashu/p/3751347.html