这章主要讲整合开发,直接从实战讲起,对与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.工程简图:

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以下的包都能够引入;

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

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

须要引入的包:

  • 3.Hibernate 4.1.6

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

须要引入的包:

  • 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:

3.entity层映射

1.须要建立三个实体类:Admin.java,Dept.java,Employee.java,例如以下:


此处都省略get和set方法: 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中加入例如以下代码令server自己主动载入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. 測试登陆

  1. 測试加入

  1. 測试删除

  1. 測试改动

好的本章介绍到这里

来自伊豚wpeace(rlovep.com)

从MVC和三层架构说到ssh整合开发-下的更多相关文章

  1. 从MVC和三层架构说到SSH整合开发

    相信很多人都认同JavaWeb开发是遵从MVC开发模式的,遵从三层架构进行开发的,是的,大家都这么认同.但是相信大家都会有过这样一个疑问,if(MVC三层模式==三层架构思想)out.println( ...

  2. 【转】浅谈MVC与三层架构

    首先给大家引入下MVC的概念: MVC(Model View Controller)模型.视图以及控制器,它是一种较为广泛应用的结构设计模式. 模型:就是在MVC设计模式中需要被显示的数据.在通常情况 ...

  3. MVC与三层架构的区别

    我们平时总是将三层架构与MVC混为一谈,殊不知它俩并不是一个概念.下面我来为大家揭晓我所知道的一些真相. 首先,它俩根本不是一个概念. 三层架构是一个分层式的软件体系架构设计,它可适用于任何一个项目. ...

  4. mvc和三层架构到底有什么区别

    原文地址:http://zhidao.baidu.com/question/82001542.html?qbl=relate_question_3&word=MVC%20%CA%FD%BE%D ...

  5. MVC与三层架构

    我们平时总是将三层架构与MVC混为一谈,殊不知它俩并不是一个概念.下面我来为大家揭晓我所知道的一些真相. 首先,它俩根本不是一个概念. 三层架构是一个分层式的软件体系架构设计,它可适用于任何一个项目. ...

  6. MVC和三层架构

    从最开始写程序到现在,一路上听到架构这个词已经无数次了,在工作和圈子里也不停听到大家在讨论它,但是很多时候发现不少人对这个概念的理解都是很模糊的,无意间在知道上看到一个朋友的回答,感觉很不错,特转帖到 ...

  7. jsp&el&jstl mvc和三层架构

    jsp:java在html中插入java 一.JSP技术 1.jsp脚本和注释 jsp脚本:(翻译成servlet,源码位置apache-tomcat-7.0.52\work\Catalina\loc ...

  8. (转)MVC 与三层架构

    原文:https://juejin.im/post/5929259b44d90400642194f3 MVC 与三层架构 一.简述 在软件开发中,MVC与三层架构这两个专业词汇经常耳闻,同时总有很多人 ...

  9. Asp.Net MVC简单三层架构(MVC5+EF6)

    三层架构与MVC的关系 三层架构是一个分层式的软件体系架构设计,分为:表现层(UI).业务逻辑层(BLL).数据访问层(DAL).分层的目的是为了实现“高内聚,低耦合”的思想,有利于系统后期的维护.更 ...

随机推荐

  1. 【大视野入门OJ】1099:歌德巴赫猜想

    Description 歌德巴赫猜想大家都很熟悉吧?给一个数,能够分解成两个素数的和.现在要给你一个n,6 <= n < 1000000,让你求他会分解成哪两个素数?如果存在多组解,则要求 ...

  2. 初见Python<3>:字符串

    1.格式化字符串 %s代表的是格式化字符串,或者说为字符串进行占位操作. 如果一个变量本身不是字符串,则会自动被转化为字符串. 使用%f格式化浮点数.同时也可以提供需要的精度,如%.3f,即保留3位小 ...

  3. [USACO 2018 Open Gold] Tutorial

    Link: 传送门 A: 对于每一条分割线,设本不应在其左侧的个数为$x$ 重点要发现每次一来一回的操作恰好会将一对分别应在左/右侧的一个数从右/左移过去 这样就转直接用树状数组求出最大的$x$即可 ...

  4. 【状压dp】CDOJ1608 暑假集训

    裸的状压的话,很显然……但有一个强大的优化. 就是在枚举决策的时候,固定第一个空位置.可以证明,这样状态数没有减少,但是降低了很多重复访问. 因为你在枚举的时候,总是可以划分为包含第一个空位置的3个位 ...

  5. session cookie的区别最全总结

    作为一名WEB开发程序员,对session的理解是最基础的,但是现状是WEB程序员遍地都是,随便一划拉一大把,不过估计能把session能透彻理解的人应该不是很多,起码我之前对此是知之甚少,偶然看到的 ...

  6. [转]XML中元素(Element)与节点(Node)的区别

    前言: element是特殊的node 一段纯文本即text-node也是node 但不是element w3c的原话是 A node can be an element node, an attri ...

  7. Ubuntu 16.04安装RedisDesktopManager

    说明:0.9版本的安装补上,只能安装0.8版本的. 官网: https://github.com/uglide/RedisDesktopManager 下载: https://github.com/u ...

  8. how to solve "[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!"

    国内私募机构九鼎控股打造APP,来就送 20元现金领取地址:http://jdb.jiudingcapital.com/phone.html内部邀请码:C8E245J (不写邀请码,没有现金送)国内私 ...

  9. iOS中 三种随机数方法详解

    ios 有如下三种随机数方法: //第一种 srand((unsigned)time(0)); //不加这句每次产生的随机数不变 int i = rand() % 5; //第二种 srandom(t ...

  10. OpenShift应用镜像构建(2) - 链式构建

    Openshift对于应用构建提供了三种模式 从应用的源代码构建并部署,Openshift通过一个S2I的构建过程编译打包并实现发布,具体可以参考 https://www.cnblogs.com/er ...