從MVC和三層架構說到ssh整合開發-下

這章主要講整合開發,直接從實戰講起,對與ssh的單方面瞭解,請繼續等待我的後續文章。

講解不到位的地方歡迎大家指正:聯繫方式rlovep.com

詳細請看源代碼註釋:

全部代碼下載(csdn):鏈接

Github鏈接:鏈接https://github.com/wpeace1212/javaBlog/tree/master/sshDemo

寫文章不易,歡迎大家採我的文章,以及給出有用的評論,當然大家也可以關注一下我的github;多謝;

1.整合流程

針對一個簡單項目,讓大家對三層機構和MVC有一個簡單的認識,以及怎樣整合ssh框架;

1.整合的項目介紹:

  1. 企業人事管理系統!要求對員工信息進行維護。
  2. 後臺系統先登陸,才能操作員工: 添加/修改/刪除
  3. 沒有登陸,只能查看列表,不能操作!

2.功能分類:
1. 管理員模塊:對應AdminAction中實現
登陸/註冊
2. 員工模塊:對應EmployeeAction中實現
添加一個員工, 指定添加的部門
對指定的員工信息修改
刪除選擇員工
列表展示

3.需要的技術:
1. Struts2:對是否登陸的攔截,對各個功能請求的分別處理,模型驅動。
2. Hibernate4:建立多對一關係的數據庫,以及實現增刪改查
表t_admin:存放管理員信息
表t_dept:存放部門信息,要用到one-to-many關聯員工表
表t_employee:存放員工信息,要用到many-to-one關聯部門表
3. Spring:實現bean對象的創建管理,整合,事務管理

4.大體按照下面的流程進行介紹:設計數據庫直接在實體存中實現

  1. Jar包引入

  2. entity層映射

  3. Spring配置

  4. hibernate配置

  5. Dao層

  6. Service層

  7. web.xml配置

  8. struts.xml配置

  9. Action層

  10. jsp層

三層架構:其中2,4,5步是數據訪問層,3,6步是業務邏輯層,7,9,10步表現層

MVC:其中2,3,4,5,6步是模型層,7,9,步是控制層,10步是視圖層

5.工程簡圖:

00

2.Jar包下載

    第一步當然是建立web項目、引入jar文件、準備環境了,建立就不介紹了,只介紹最小包的引入:
我的最小包下載地址(ssh最小包):http://download.csdn.net/detail/peace1213/9412092

  • 1.Struts 2.3.16.1

下載地址:http://struts.apache.org/download

Struts中需要引入的包:struts-2.3.16.1/apps/struts2-blank/WEB-INF/lib:該lib下面的包都可以引入;

01

  • 2.spring-framework-4.2.3.RELEASE-dist.zip

下載地址:http://repo.springsource.org/libs-release-local/org/springframework/spring/

需要引入的包:

03

  • 3.Hibernate 4.1.6

下載地址:http://sourceforge.net/projects/hibernate/files/hibernate4

需要引入的包:

02

  • 4.Aopalliance 1.0

該包在struts的lib中有

下載地址:http://sourceforge.net/projects/aopalliance


aopalliance.jar
  • 5.Aspectj 1.7.0

下載地址:http://www.eclipse.org/aspectj/downloads.php


aspectjrt.jar  

aspectjweaver.jar
  • 6.Cglib 2.2.3

下載地址:http://sourceforge.net/projects/cglib/files


cglib-2.2.3.jar
  • 7.Asm 3.3

該包在struts的lib中有

下載地址:http://forge.ow2.org/projects/asm


asm-3.3.jar
  • 8.Log4j 1.2.17

該包在struts的lib中有

下載地址:http://logging.apache.org/log4j/1.2/download.html


log4j-1.2.17.jar
  • 9.mysql-connector-java-5.1.37-bin.jar

下載地址:http://dev.mysql.com/downloads/connector/j


mysql-connector-java-5.1.37-bin.jar
  • 10.Commons Logging 1.1.1

該包在struts的lib中有

下載地址:http://commons.apache.org/logging


commons-logging-1.1.1.jar

其他需要引入的jar:

04

3.entity層映射

1.需要建立三個實體類:Admin.java,Dept.java,Employee.java,如下:


此處都省略getset方法:

public class Admin {

    private int id;

    private String adminName;

    private String pwd;

......

public class Dept {

    private int id;

    private String name;

    private Set<Employee> emps=new LinkedHashSet<>();

......



public class Employee {

    private int id;

    private String empName;

    private double salary;

    private Dept dept;

......

2.建立對應的映射文件:×.hbm.xml


1.Admin.hbm.xml:



<class name="Admin" table="t_admin">

        <id name="id">

            <generator class="native"></generator>

        </id>

        <property name="adminName" length="20"></property>

        <property name="pwd" length="20"></property>

    </class>

2.Dept.hbm.xml:



   <class name="Dept" table="t_dept">

       <id name="id" >

          <generator class="native"></generator>

       </id>

       <property name="name" column="Dname"></property>

       <set name="emps" cascade="save-update,delete" table="t_employee" >

           <key column="dept_id"></key>

           <one-to-many class="Employee"></one-to-many>

       </set>

3.Employee.hbm.xml:



 <class name="Employee" table="t_employee">

       <id name="id">

        <generator class="native"></generator>

       </id>

      <property name="empName"  length="20"></property>

        <property name="salary" type="double"></property> 

        <many-to-one name="dept" column="dept_id" class="Dept"></many-to-one>

   </class>

4.Spring配置 :

Spring分爲:bean-base.xml,bean-dao.xml,bean-service.xml,bean-action.xml,以及整合成一個的bean.xml

辭去暫時介紹bean-base.xml基礎功能文件和bean.xml,其他文件到相應的介紹地方再進行介紹;

1.bean-base.xml:主要配置Hibernate的工廠sessionFactory和事務,連接池


<?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:p="http://www.springframework.org/schema/p"

    xmlns:context="http://www.springframework.org/schema/context"

    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.xsd

         http://www.springframework.org/schema/context

         http://www.springframework.org/schema/context/spring-context.xsd

         http://www.springframework.org/schema/aop

         http://www.springframework.org/schema/aop/spring-aop.xsd

         http://www.springframework.org/schema/tx

         http://www.springframework.org/schema/tx/spring-tx.xsd">

         <!-- 1. 數據源對象: C3P0連接池 -->

        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">

            <property name="driverClass" value="com.mysql.jdbc.Driver"></property>

            <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/day01?useUnicode=true&amp;characterEncoding=UTF8"></property>

            <property name="user" value="root"></property>

            <property name="password" value="123456"></property>

            <property name="initialPoolSize" value="3"></property>

            <property name="maxPoolSize" value="10"></property>

            <property name="maxStatements" value="100"></property>

            <property name="acquireIncrement" value="2"></property>

                </bean>

                <!-- ###########Spring與Hibernate整合  start########### -->

    <!-- 【推薦】方式所有的配置全部都在Spring配置文件中完成 -->

    <bean id="sessionFactory"

        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">

        <!-- 注入連接池對象 -->

        <property name="dataSource" ref="dataSource"></property>

        <!-- Hibernate常用配置 -->

        <property name="hibernateProperties">

            <props>

                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>

                <prop key="hibernate.show_sql">true</prop>

                <prop key="hibernate.hbm2ddl.auto">update</prop>

            </props>

        </property>

     <!-- hibernate映射配置--> 

        <property name="mappingLocations">

            <list>

                <value>classpath:com/rlovep/entity/*.hbm.xml</value>

            </list>

        </property>

        </bean>

<!-- ###########Spring與Hibernate整合  end########### -->

        <!-- 事務配置 -->

    <!-- a. 配置事務管理器類 -->

    <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">

        <property name="sessionFactory" ref="sessionFactory"></property>

    </bean>

    <!-- b. 配置事務增強(攔截到方法後如果管理事務?) -->

    <tx:advice id="txAdvice" transaction-manager="txManager">

        <tx:attributes>

            <tx:method name="*" read-only="false"/>

        </tx:attributes>

    </tx:advice>

    <!-- c. Aop配置 -->

    <aop:config>

         <aop:pointcut expression="execution(* com.rlovep.service.impl.*.*(..))" id="pt"/>

         <aop:advisor advice-ref="txAdvice" pointcut-ref="pt"/>

    </aop:config>

         <!-- 用於建表 -->

      <bean id="appDao" class="com.rlovep.entity.AppDao">

            <property name="sessionFactory" ref="sessionFactory"></property>

          </bean>

 </beans>

2.bean.xml:


....省略.....

    <!-- 引入其他配置文件 -->

    <import resource="config/bean-base.xml"/>

    <import resource="config/bean-dao.xml"/>

    <import resource="config/bean-service.xml"/>

    <import resource="config/bean-action.xml"/>

</beans>   

5.Hibernate配置:

Spring中已經配置好了Hibernate,此處主要講解建立數據庫中的三個表;

  1. 建立AppDao類文件:bean已經在bean.hbm.xml中配置了

/*

 * 用來創建數據庫中的表

 */

public class AppDao {

    //工廠通過spring注入

    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {

        this.sessionFactory = sessionFactory;

    }

    //@Test

    public void test(){

        //sessionFactory=(SessionFactory)ac.getBean("sessionFactory");

        Session session = sessionFactory.openSession();

        Transaction tx = session.beginTransaction();

        //保存管理員,並創建表

        Admin admin=new Admin();

        admin.setAdminName("admin");

        admin.setPwd("123456");

        session.save(admin);

        //保存部門和僱員,並創建表

        Dept dept1=new Dept();

        Dept dept2=new Dept();

....省略.....

//持久化

        session.save(dept1);

....省略.....

        session.save(employee4);

        tx.commit();

        session.close();

    }

2.建立類App類創建數據庫和存數據:


public class App {

    private ApplicationContext ac=new ClassPathXmlApplicationContext("config/bean-base.xml");

    @Test

    public void test(){

        //ac.getBean("deptDao");

        AppDao appDao = (AppDao)ac.getBean("appDao");

        appDao.test();

    }

}

3.點擊運行App的test方法就可以完成數據庫的創建;

6.Dao層:實現數據增刪改查;

1.先建立接口: IAdminDao,IDepDao,IEmployee,IBaseDao(所有Dao的通用操作接口定義)

此處只貼出IBaseDao接口的定義:


/*

 * * 所有dao的通用操作接口定義

 */

public interface IBaseDao<T> {

    /**

     * 保存

     * @param obj

     */

    void save(T obj);



....省略.....

}

2.接口的實現:AdminDao,DepDao,Employee,BaseDao(所有Dao的通用操作,希望所有的dao都繼承此類)

BaseDao實現:


/*

 * 所有dao的通用操作,希望所有的dao都繼承此類

 */

public class BaseDao<T> implements IBaseDao<T>{

    //當前操作實際的bean類型

    private Class<T>clazz;

    //獲取類名稱

    private String className;

    // IOC容器(依賴)注入SessionFactory對象

    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {

        this.sessionFactory = sessionFactory;

    }

     public BaseDao() {

        Type type=this.getClass().getGenericSuperclass();

        //轉換爲參數化類型

        ParameterizedType pt=(ParameterizedType)type;// BaseDao<Employee>

        //得到實際類型

        Type types[]=pt.getActualTypeArguments();

        //獲取實際類型

        clazz=(Class<T>)types[0];

        className = clazz.getSimpleName();//例如:Employee

    }

....省略.....

    @Override

    public List<T> getAll() {

        Query query = sessionFactory.getCurrentSession().createQuery("from "+className);

        List<T> list = query.list();

        return list;

    }

}

其他接口實現:



//只需要繼承通用操作,和特點接口就行:這裏接口中沒有方法,可以加方法

public class DeptDao extends BaseDao<Dept> implements IDepDao{

}

7.Service層:

同樣先建立接口再建立類,此處不貼出代碼,介紹bean-dao.xml,bean-service.xml的建立,以及對剛剛建立的Dao和service進行測試

1.bean-dao.xml



 <!-- dao實例 -->

         <bean id="adminDao" class="com.rlovep.dao.impl.AdminDao">

             <property name="sessionFactory" ref="sessionFactory"></property>

          </bean>

          <bean id="deptDao" class="com.rlovep.dao.impl.DeptDao">

             <property name="sessionFactory" ref="sessionFactory"></property>

          </bean>

          <bean id="employeeDao" class="com.rlovep.dao.impl.EmployeeDao">

             <property name="sessionFactory" ref="sessionFactory"></property>

          </bean>

2.bean-service.xml



 <!-- service 實例 -->

          <bean id="adminService" class="com.rlovep.service.impl.AdminService">

            <property name="adminDao" ref="adminDao"></property>

          </bean>

           <bean id="deptService" class="com.rlovep.service.impl.DeptService">

            <property name="deptDao" ref="deptDao"></property>

          </bean>

           <bean id="employeeService" class="com.rlovep.service.impl.EmployeeService">

            <property name="employeeDao" ref="employeeDao"></property>

          </bean>

3.測試剛剛建立的dao和service:

在包service中建立App測試類:



public class App {

    //加載spring的配置文件

   private ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");

   //測試Admin的操作

   @Test

   public void testAdmin(){

       //獲得bean

     IAdminService adminService=(IAdminService)ac.getBean("adminService");

     Admin admin=new Admin();

     admin.setAdminName("admin");

     admin.setPwd("123456");

    System.out.println( adminService.login(admin));

   }

   //測試Dept的操作

   @Test

   public void testDept(){

     IDeptService service=( IDeptService)ac.getBean("deptService");

    System.out.println( service.findById(1));

   }

   //測試Employee的操作

   @Test

   public void testEmployee(){

     IEmployeeService service=( IEmployeeService)ac.getBean("employeeService");

     List<Employee> list = service.getAll();

    System.out.println( service.findById(9));

   }

}

8.web.xml配置:

  1. 需要配置Spring

  2. 需要配置Struts2

  3. 配置文件如下:


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

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">

  <display-name>sshDemo</display-name>

  <!-- 配置spring的OpenSessionInView模式 【目的:JSp頁面訪問懶加載數據】 -->

        <!-- 注意:訪問struts時候需要帶上*.action後綴 -->

        <filter>

            <filter-name>OpenSessionInView</filter-name>

            <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>

        </filter>

        <filter-mapping>

            <filter-name>OpenSessionInView</filter-name>

            <url-pattern>*.action</url-pattern>

        </filter-mapping>

              <!-- Struts2的配置 -->

          <filter>

          <!-- 配置過濾器的名字 -->

            <filter-name>struts2</filter-name>

          <!--  配置核心過濾器類 -->

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

          </filter>

        <!--配置要攔截的URL,辭去配置全部攔截 -->

          <filter-mapping>

              <filter-name>struts2</filter-name>

              <url-pattern>/*</url-pattern>

          </filter-mapping>

            <!--在web.xml中加入如下代碼令服務器自動加載Spring   --> 

        <context-param>

            <param-name>contextConfigLocation</param-name>

            <param-value>classpath:bean.xml</param-value>

        </context-param>

        <listener>

            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

        </listener>

         <!-- 首頁配置 -->

    <welcome-file-list>

        <welcome-file>index.jsp</welcome-file>

    </welcome-file-list>

</web-app>

9.struts.xml配置 :

1.由於spring的整合,在 struts.xml配置文件中的class屬性直接使用:spring的配置文件bean-action.xml中定義的bean

2.struts.xml文件:


<package name="struts2" extends="struts-default">

<!-- 配置action,class屬性使用Spring中定義的bean->

      <action name="admin_*" class="adminAction" method="{1}">

       <!-- 登陸失敗 -->

            <result name="loginFaild">/login.jsp</result>

            <!-- 登陸成功 -->

            <result name="index" type="redirectAction">emp_list</result>

      </action>

       <action name="emp_*" class="employeeAction" method="{1}">

           <!-- 列表展示 -->

            <result name="list">/WEB-INF/list.jsp</result>

            <!-- 進入添加頁面視圖 -->

            <result name="add">/WEB-INF/add.jsp</result>

            <!-- 添加成功,進入列表 (防止刷新就多一條記錄問題,所以用重定向) -->

            <result name="listAction" type="redirectAction">emp_list</result>       

            <!-- 進入修改頁面 -->

            <result name="edit">/WEB-INF/edit.jsp</result>

      </action>

3.bean-action.xml文件:


    <!-- 指定action多例 -->

    <bean id="adminAction" class="com.rlovep.action.AdminAction" scope="prototype">

        <property name="adminService" ref="adminService"></property>

    </bean>

    <bean id="employeeAction" class="com.rlovep.action.EmployeeAction" scope="prototype">

        <property name="deptService" ref="deptService"></property>

        <property name="employeeService" ref="employeeService"></property>

    </bean>

10.Action層 :

  1. 建立AdminAction文件:繼承ActionSupport類,和實現ModelDriver接口

  2. 建立EmployeeAction文件:繼承ActionSupport類,和實現ModelDriver接口

  3. 建立攔截器類:AdminInterceptor類用於判斷是否登陸;繼承AbstractInterceptor


@Override

    public String intercept(ActionInvocation invocation) throws Exception {

        //得到當前執行的方法

        String method = invocation.getProxy().getMethod();

        //判斷:當不爲登陸方法和list方法時

        if(!"login".equals(method)&&!"list".equals(method)){

            Object obj= ActionContext.getContext().getSession().get("adminInfo");

            if(obj==null){

                //沒有登陸

                return "login";

            }else{

                //放行

                return invocation.invoke();

            }

        }

        //放行

        return invocation.invoke();

    }

11.建立相應的jsp文件:

主要有:index,login,edit,add,list等jsp文件;詳情見工程源代碼;

11.測試圖:部署動態工程

  1. 測試登陸

4

  1. 測試添加

5

  1. 測試刪除

6

  1. 測試修改

7

好的本章介紹到這裏
來自伊豚wpeace(rlovep.com)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章