首页 > 代码库 > SSH整合
SSH整合
首先,SSH不是一个框架,而是多个框架(struts+spring+hibernate)的集成,是目前较流行的一种Web应用程序开源集成框架,用于构建灵活、易于扩展的多层Web应用程序。
集成SSH框架的系统从职责上分为四层:表示层、业务逻辑层、数据持久层和实体层。
由SSH构建系统的基本业务流程是:
1、在表示层中,首先通过JSP页面实现交互界面,负责传送请求(Request)和接收响应(Response),然后Struts根据配置文件(struts-config.xml)将ActionServlet接收到的Request委派给相应的Action处理。
2、在业务层中,管理服务组件的Spring IoC容器负责向Action提供业务模型(Model)组件和该组件的协作对象数据处理(DAO)组件完成业务逻辑,并提供事务处理、缓冲池等容器组件以提升系统性能和保证数据的完整性。
3、在持久层中,则依赖于Hibernate的对象化映射和数据库交互,处理DAO组件请求的数据,并返回处理结果。
下面我们了解一下组成SSH的三个框架
Spring是一个轻量级的控制反转(ioc)和面向切面(aop)的容器框架。
Spring特性
为什么说Spring?
Spring的以上特性是开发人员使用基本的JavaBean来完成以前只可能由EJB完成的事情。然而,Spring的用途不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何Java应用都可以从Spring中受益。
Struts
它通过采用 Java Servlet/JSP 技术,实现了基于Java EEWeb应用的MVC设计模式的应用框架,是MVC经典设计模式中的一个经典产品。
struts1的核心构成
Struts2
Struts 2是Struts的下一代产品,是在 struts 1和WebWork的技术基础上进行了合并的全新的Struts 2框架。其全新的Struts 2的体系结构与Struts 1的体系结构差别巨大。Struts 2以WebWork为核心,采用拦截器的机制来处理用户的请求,这样的设计也使得业务逻辑控制器能够与ServletAPI完全脱离开,所以Struts 2可以理解为WebWork的更新产品
Struts2体系结构
Hibernate
Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库。 Hibernate可以应用在任何使用JDBC的场合,既可以在Java的客户端程序使用,也可以在Servlet/JSP的Web应用中使用,最具革命意义的是,Hibernate可以在应用EJB的J2EE架构中取代CMP,完成数据持久化的重任
Hibernate核心构成
hibernate基本执行流程
下面看以一个案例来了解一下SSH框架整合
项目整体架构
实体类
package cn.happy.beans; import javax.annotation.Generated; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import org.hibernate.annotations.GenericGenerator; /** * 股票 * @author Happy */ public class Stock { private int sid; private String sname; private int count; //股数 public int getSid() { return sid; } public void setSid(int sid) { this.sid = sid; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="cn.happy.beans"> <class name="Stock"> <id name="sid"> <generator class="native"></generator> </id> <property name="sname" column="SNAME"></property> <property name="count" column="COUNT"></property> </class> </hibernate-mapping>
Dao/DaoImpl
package cn.happy.dao; import cn.happy.beans.Stock; /** *股票 * @author xiaobai * */ public interface IStockDAO { //创建股票 public int addStock(Stock stock); }
package cn.happy.dao.impl; import java.io.Serializable; import org.hibernate.SessionFactory; import org.springframework.jdbc.core.support.JdbcDaoSupport; import cn.happy.beans.Stock; import cn.happy.dao.IStockDAO; public class StockDAOImpl implements IStockDAO { private SessionFactory sessionFactory; @Override public int addStock(Stock stock) { Serializable count = sessionFactory.getCurrentSession().save(stock); return ((Integer)count).intValue(); } public SessionFactory getSessionFactory() { return sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } }
service/serviceImpl
package cn.happy.service; import cn.happy.beans.Stock; /** * 股票 * @author xiaobai * */ public interface IStockService { //02.添加股票 public int addStock(Stock stock); }
package cn.happy.service.impl; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import cn.happy.beans.Stock; import cn.happy.dao.IStockDAO; import cn.happy.service.IStockService; public class StockServiceImpl implements IStockService { //植入dao对象 private IStockDAO stockDao; @Override //@Transactional(isolation=Isolation.DEFAULT,propagation=Propagation.REQUIRED) public int addStock(Stock stock) { return stockDao.addStock(stock); } public IStockDAO getStockDao() { return stockDao; } public void setStockDao(IStockDAO stockDao) { this.stockDao = stockDao; } }
测试类(test)
package cn.happy.test; import java.util.List; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import cn.happy.beans.Stock; import cn.happy.service.IStockService; public class MyTest { @Test //购入股票 public void addData(){ ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml"); IStockService service=(IStockService)ctx.getBean("stockService"); Stock stock=new Stock(); stock.setSname("程序开发"); stock.setCount(50); int addStock = service.addStock(stock); System.out.println(addStock); } }
配置文件
<?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: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"> <!-- 4.注册jdbc属性 --> <context:property-placeholder location="classpath:jdb.properties"/> <!-- 1.c3p0数据源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="http://www.mamicode.com/${jdbc.driver}"></property> <property name="jdbcUrl" value="http://www.mamicode.com/${jdbc.url}"></property> <property name="user" value="http://www.mamicode.com/${jdbc.username}"></property> <property name="password" value="http://www.mamicode.com/${jdbc.password}"></property> </bean> <!-- SessionFactory配置 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <!-- 数据源 --> <property name="dataSource" ref="dataSource"></property> <!--各种hibernate属性 --> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.current_session_context_class"> org.springframework.orm.hibernate3.SpringSessionContext</prop> </props> </property> <!-- 引入小配置 --> <!-- <property name="mappingResources" value="http://www.mamicode.com/cn/happy/beans/Stock.hbm.xml"></property> --> <property name="mappingDirectoryLocations" value="http://www.mamicode.com/classpath:cn/happy/beans"></property> </bean> <bean id="stockDao" class="cn.happy.dao.impl.StockDAOImpl"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 2.service --> <bean id="service" class="cn.happy.service.impl.StockServiceImpl"> <property name="stockDao" ref="stockDao"></property> </bean> <!-- Action中注入service --> <bean id="addStock" class="cn.happy.action.AddStockAction" scope="prototype"> <property name="service" ref="service"></property> </bean> <!--事务配置 --> <!-- 注册事务管理器 --> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <!--指定在连接方法上应用的事务属性 --> <tx:method name="addStock" isolation="DEFAULT" propagation="REQUIRED"/> </tx:attributes> </tx:advice> <!-- aop配置 --> <aop:config> <aop:pointcut expression="execution(* *..service.*.*(..))" id="stockPointcut"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="stockPointcut"/> </aop:config> </beans>
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc\:mysql\:///表名 jdbc.username=用户名 jdbc.password=密码
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <package name="default" extends="struts-default"> <!-- Action --> <action name="addStockAction" class="addStock" method="add"> <result name="success">/index.jsp</result> </action> </package> </struts>
web.xml配置
<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <display-name></display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!--指定配置文件的位置和名称 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- 监听器:作用是在整个网站运行的时候,获取到ServletContext(application)初始化的时候,自动 注入Spring容器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <filter> <filter-name>struts</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <%@ taglib uri="/struts-tags" prefix="s"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP ‘add.jsp‘ starting page</title> </head> <body> <h1>添加</h1> <s:form action="addStockAction" method="post"> <s:textfield name="stock.sname"/> <s:textfield name="stock.count"/> <s:submit value="提交"></s:submit> </s:form> </body> </html>
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP ‘index.jsp‘ starting page</title> </head> <body> 成功 <br> </body> </html>
运行结果展示:
SSH整合