SSH框架笔记01

mac2022-06-30  14

目录

1. 框架回顾2. 创建项目,引入jar包 2.1 Struts2的jar包2.2 Hibernate的jar包2.3 Spring的jar包3. 引入配置文件 3.1 Struts2配置的文件3.2 Hibernate的配置文件3.3 Spring的配置文件4. 创建包结构5. 创建相关类,引入页面6. Spring整合Struts2 6.1 Spring整合Struts2方式一:Action由Struts2自身创建6.2 Spring整合Struts2方式二:Action交给Spring管理【推荐】7. Service调用Dao8. Spring整合Hibernate 8.1 创建数据库和表8.2 编写实体和映射8.3 Spring和Hibernate整合8.4 配置Spring的事务管理器9. SSH整合方式二:将Hibernate的配置交给Spring管理 9.1 复制一个项目9.2 将Hibernate的相关属性的配置转移到Spring9.3 Spring的配置文件最终版

1. 框架回顾

2. 创建项目,引入jar包

2.1 Struts2的jar包

基础包:..\struts2\struts-2.3.24-apps\struts-2.3.24\apps\struts2-blank\WEB-INF\lib\*.jar asm-3.3.jarasm-commons-3.3.jarasm-tree-3.3.jarcommons-fileupload-1.3.1.jarcommons-io-2.2.jarcommons-lang3-3.2.jarfreemarker-2.3.22.jarjavassist-3.11.0.GA.jarlog4j-api-2.2.jarlog4j-core-2.2.jarognl-3.0.6.jarstruts2-core-2.3.24.jarxwork-core-2.3.24.jar 其他..\struts2\struts-2.3.24\lib Struts2的注解开发包struts2-convention-plugin-2.3.24.jarStruts2的整合AJAX的开发包struts2-json-plugin-2.3.24.jarStruts2的整合Spring的开发包struts2-spring-plugin-2.3.24.jar

2.2 Hibernate的jar包

必须的包:..\hibernate-release-5.0.7.Final\lib\required antlr-2.7.7.jardom4j-1.6.1.jargeronimo-jta_1.1_spec-1.1.1.jarhibernate-commons-annotations-5.0.1.Final.jarhibernate-core-5.0.7.Final.jarhibernate-jpa-2.1-api-1.0.0.Final.jarjandex-2.0.0.Final.jarjavassist-3.18.1-GA.jarjboss-logging-3.3.0.Final.jar MySQL驱动包:mysql-connector-java-5.0.4-bin.jar日志包: log4j-1.2.16.jarslf4j-api-1.6.1.jarslf4j-log4j12-1.7.2.jar 使用C3P0连接池:..\hibernate-release-5.0.7.Final\lib\optional\c3p0\*.jar c3p0-0.9.2.1.jarhibernate-c3p0-5.0.7.Final.jarmchange-commons-java-0.2.3.4.jar 注意:Struts2和Hibernate都引入了一个相同的jar包(javassist包)。删除一个。

2.3 Spring的jar包

IOC的开发 ..\spring-framework-4.2.4.RELEASE-dist\spring-framework-4.2.4.RELEASE\libsspring-beans-4.2.4.RELEASE.jar..\spring-framework-4.2.4.RELEASE-dist\spring-framework-4.2.4.RELEASE\libsspring-context-4.2.4.RELEASE.jar..\spring-framework-4.2.4.RELEASE-dist\spring-framework-4.2.4.RELEASE\libsspring-core-4.2.4.RELEASE.jar..\spring-framework-4.2.4.RELEASE-dist\spring-framework-4.2.4.RELEASE\libsspring-expression-4.2.4.RELEASE.jar..\spring相关依赖包\spring-framework-3.0.2.RELEASE-dependencies\org.apache.log4j\com.springsource.org.apache.log4j\1.2.15com.springsource.org.apache.log4j-1.2.15.jar..\spring相关依赖包\spring-framework-3.0.2.RELEASE-dependencies\org.apache.commons\com.springsource.org.apache.commons.logging\1.1.1com.springsource.org.apache.commons.logging-1.1.1.jar AOP的开发 ..\spring相关依赖包\spring-framework-3.0.2.RELEASE-dependencies\org.aopalliance\com.springsource.org.aopalliance\1.0.0com.springsource.org.aopalliance-1.0.0.jar..\spring相关依赖包\spring-framework-3.0.2.RELEASE-dependencies\org.aspectj\com.springsource.org.aspectj.weaver\1.6.8.RELEASEcom.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar..\spring-framework-4.2.4.RELEASE-dist\spring-framework-4.2.4.RELEASE\libsspring-aop-4.2.4.RELEASE.jar..\spring-framework-4.2.4.RELEASE-dist\spring-framework-4.2.4.RELEASE\libsspring-aspects-4.2.4.RELEASE.jar JDBC模板的开发 ..\spring-framework-4.2.4.RELEASE-dist\spring-framework-4.2.4.RELEASE\libsspring-jdbc-4.2.4.RELEASE.jar..\spring-framework-4.2.4.RELEASE-dist\spring-framework-4.2.4.RELEASE\libsspring-tx-4.2.4.RELEASE.jar

事务管理:

..\spring-framework-4.2.4.RELEASE-dist\spring-framework-4.2.4.RELEASE\libs\spring-tx-4.2.4.RELEASE.jar

整合web项目的开发

..\spring-framework-4.2.4.RELEASE-dist\spring-framework-4.2.4.RELEASE\libs\spring-web-4.2.4.RELEASE.jar

整合单元测试的开发

..\spring-framework-4.2.4.RELEASE-dist\spring-framework-4.2.4.RELEASE\libs\spring-test-4.2.4.RELEASE.jar

整合Hibernate的开发

..\spring-framework-4.2.4.RELEASE-dist\spring-framework-4.2.4.RELEASE\libs\spring-orm-4.2.4.RELEASE.jar

3. 引入配置文件

3.1 Struts2配置的文件

web.xml <!-- 配置Struts2的核心过滤器 --> <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.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <!-- 配置Struts2的常量 --> <constant name="struts.action.extension" value="action"/> </struts>

3.2 Hibernate的配置文件

hibernate.cfg.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- 连接数据库的基本参数 --> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql:///ssh1</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">2626</property> <!-- 配置Hibernate的方言 --> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <!-- 可选配置================ --> <!-- 打印SQL --> <property name="hibernate.show_sql">true</property> <!-- 格式化SQL --> <property name="hibernate.format_sql">true</property> <!-- 自动创建表 --> <property name="hibernate.hbm2ddl.auto">update</property> <!-- 配置C3P0连接池 --> <property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property> <!--在连接池中可用的数据库连接的最少数目 --> <property name="c3p0.min_size">5</property> <!--在连接池中所有数据库连接的最大数目 --> <property name="c3p0.max_size">20</property> <!--设定数据库连接的过期时间,以秒为单位, 如果连接池中的某个数据库连接处于空闲状态的时间超过了timeout时间,就会从连接池中清除 --> <property name="c3p0.timeout">120</property> <!--每3000秒检查所有连接池中的空闲连接 以秒为单位--> <property name="c3p0.idle_test_period">3000</property> <!-- 引入映射 --> </session-factory> </hibernate-configuration>

删除那个与线程绑定的session

映射文件

3.3 Spring的配置文件

web.xml <!-- Spring的核心监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 加载Spring的配置文件的路径的,默认加载的/WEB-INF/applicationContext.xml --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> applicationContext.xml <?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"> </beans> 日志记录:log4j.properties ### direct log messages to stdout ### log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.err log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### direct messages to file mylog.log ### log4j.appender.file=org.apache.log4j.FileAppender log4j.appender.file.File=c\:mylog.log log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### set log levels - for more verbose logging change 'info' to 'debug' ### # error warn info debug trace log4j.rootLogger= info, stdout

4. 创建包结构

5. 创建相关类,引入页面

6. Spring整合Struts2

6.1 Spring整合Struts2方式一:Action由Struts2自身创建

编写Action:CustomerAction package com.itzhouq.web.action; import com.itzhouq.domain.Customer; /** * 客户管理的Action类 */ import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; public class CustomerAction extends ActionSupport implements ModelDriven<Customer> { // 模型驱动使用的对象 private Customer customer = new Customer(); @Override public Customer getModel() { return customer; } /** * 保存客户的方法:save */ public String save() { System.out.println("Action的save方法执行了。。。。"); return NONE; } } 配置Action:在struts.xml中配置 <!-- 配置Action --> <package name="ssh1" extends="struts-default" namespace="/"> <action name="customer_*" class="com.itzhouq.web.action.CustomerAction" method="{1}"> </action> </package> 在Action中引入Service----传统方式 // 如果web层没有使用Struts2,获取业务层的类就必须如下进行编写: WebApplicationContext applicationContext = WebApplicationContextUtils .getWebApplicationContext(ServletActionContext.getServletContext()); CustomerService customerService = (CustomerService) applicationContext.getBean("customerService"); 在Action中引入Service----Spring和Struts2整合 引入Spring整合Struts2的jar包struts2-spring-plugin-2.3.24.jar在插件包中有如下配置 <!-- Make the Spring object factory the automatic default --> <constant name="struts.objectFactory" value="spring" /> 开启一个常量:在Struts2中只有开启这个常量就会引发下面常量生效,在Struts2核心包下default.properties

将Service交给Spring管理,让Action按照名称自动注入Service。在Spring的配置文件中做如下配置。 <!-- 配置Service================ --> <bean id="customerService" class="com.itzhouq.service.impl.CustomerServiceImpl"> </bean> Action注入Servcie package com.itzhouq.web.action; import org.apache.struts2.ServletActionContext; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import com.itzhouq.domain.Customer; import com.itzhouq.service.CustomerService; /** * 客户管理的Action类 */ import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; public class CustomerAction extends ActionSupport implements ModelDriven<Customer> { // 模型驱动使用的对象 private Customer customer = new Customer(); @Override public Customer getModel() { return customer; } // 注入customerService private CustomerService customerService; public void setCustomerService(CustomerService customerService) { this.customerService = customerService; } /** * 保存客户的方法:save */ public String save() { System.out.println("Action的save方法执行了。。。。"); // 如果web层没有使用Struts2,获取业务层的类就必须如下进行编写: // WebApplicationContext applicationContext = WebApplicationContextUtils // .getWebApplicationContext(ServletActionContext.getServletContext()); // CustomerService customerService = (CustomerService) applicationContext.getBean("customerService"); customerService.save(customer); return NONE; } }

6.2 Spring整合Struts2方式二:Action交给Spring管理【推荐】

引入Spring整合Struts2的jar包struts2-spring-plugin-2.3.24.jar

将Action交给Spring管理,在Spring的配置文件中配置

<!-- 配置Action============= --> <bean id="customerAction" class="com.itzhouq.web.action.CustomerAction" scope="prototype" > <!-- 手动注入Service --> <property name="customerService" ref="customerService"/> </bean> 在struts.xml中配置,class属性变为Spring中的id的值 <!-- 配置Action --> <package name="ssh1" extends="struts-default" namespace="/"> <action name="customer_*" class="customerAction" method="{1}"> </action> </package> 注意: 需要配置Action为多例的需要手动注入Service

7. Service调用Dao

将Dao交给Spring管理:applicationContext.xml中添加配置 <!-- 配置Dao --> <bean id="customerDao" class="com.itzhouq.dao.impl.CustomerDaoImpl"> </bean> 在Service层注入Dao:CustomerServiceImpl中注入 public class CustomerServiceImpl implements CustomerService { // 注入Dao private CustomerDao customerDao; public void setCustomerDao(CustomerDao customerDao) { this.customerDao = customerDao; } @Override public void save(Customer customer) { System.out.println("Service中的save方法执行了。。。。。"); } } 注入配置 <!-- 配置Service================ --> <bean id="customerService" class="com.itzhouq.service.impl.CustomerServiceImpl"> <property name="customerDao" ref="customerDao"></property> </bean>

8. Spring整合Hibernate

8.1 创建数据库和表

Create database ssh1; Use ssh1; CREATE TABLE `cst_customer` ( `cust_id` bigint(32) NOT NULL AUTO_INCREMENT COMMENT '客户编号(主键)', `cust_name` varchar(32) NOT NULL COMMENT '客户名称(公司名称)', `cust_source` varchar(32) DEFAULT NULL COMMENT '客户信息来源', `cust_industry` varchar(32) DEFAULT NULL COMMENT '客户所属行业', `cust_level` varchar(32) DEFAULT NULL COMMENT '客户级别', `cust_phone` varchar(64) DEFAULT NULL COMMENT '固定电话', `cust_mobile` varchar(16) DEFAULT NULL COMMENT '移动电话', PRIMARY KEY (`cust_id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

8.2 编写实体和映射

public final class Customer { private Long cust_id; private String cust_name; private String cust_source; private String cust_industry; private String cust_level; private String cust_phone; private String cust_mobile; //set/get方法 } com/itzhouq/domain/Customer.hbm.xml <?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> <!-- 建立类与表的映射 --> <class name="com.itzhouq.domain.Customer" table="cst_customer"> <!-- 建立类中的属性与表中的主键对应 --> <id name="cust_id" column="cust_id" > <!-- 主键生成策略 --> <generator class="native"/> </id> <!-- 建立类中的普通的属性和表的字段的对应 --> <property name="cust_name" column="cust_name" /> <property name="cust_source" column="cust_source"/> <property name="cust_industry" column="cust_industry"/> <property name="cust_level" column="cust_level"/> <property name="cust_phone" column="cust_phone"/> <property name="cust_mobile" column="cust_mobile"/> </class> </hibernate-mapping> 在hibernate.cfg.xml中引入映射文件 <!-- 引入映射 --> <mapping resource="com/itzhouq/domain/Customer.hbm.xml"/>

8.3 Spring和Hibernate整合

在Spring的配置文件application.xml中引入Hibernate的配置信息 <!-- Spring整合Hibernate --> <!-- 引入Hibernate的配置的信息=============== --> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <!-- 引入hibernate的配置文件 --> <property name="configLocation" value="classpath:hibernate.cfg.xml"/> </bean> 在Spring和Hibernate整合后,Spring提供了一个Hibernate的模板类简化Hibernate开发改写DAO继承HibernateDaoSupport public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao { @Override public void save(Customer customer) { System.out.println("Dao中的save方法执行了。。。。"); } } 配置的时候在DAO中直接注入SessionFactory:注入SessionFactory就会创建Hibernate模板。 <!-- 配置Dao --> <bean id="customerDao" class="com.itzhouq.dao.impl.CustomerDaoImpl"> <property name="sessionFactory" ref="sessionFactory"/> </bean> 在DAO中使用Hibernate的模板完成保存操作 package com.itzhouq.dao.impl; import org.springframework.orm.hibernate5.support.HibernateDaoSupport; /** * 客户管理的dao层的实现类 * @author itzhouq * */ import com.itzhouq.dao.CustomerDao; import com.itzhouq.domain.Customer; public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao { @Override public void save(Customer customer) { System.out.println("Dao中的save方法执行了。。。。"); this.getHibernateTemplate().save(customer); } }

8.4 配置Spring的事务管理器

配置事务管理器,开启注解事务 <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!-- 开启注解事务 --> <tx:annotation-driven transaction-manager="transactionManager"/> 在业务层使用注解 @Transactional public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao {

9. SSH整合方式二:将Hibernate的配置交给Spring管理

9.1 复制一个项目

复制一个项目,并修改Properties ---- Web Project Settings-----Comtext Root的名称

9.2 将Hibernate的相关属性的配置转移到Spring

数据库连接的配置:使用jdbc.properties jdbc.driverClass=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql:///ssh1 jdbc.username=root jdbc.password=2626 在Spring中引入 <!-- 引入外部属性文件=============================== --> <context:property-placeholder location="classpath:jdbc.properties"/> C3P0连接池:在Spring中 <!-- 配置C3P0连接池=============================== --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driverClass}"/> <property name="jdbcUrl" value="${jdbc.url}"/> <property name="user" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> 整合Hibernate的配置 <!-- Spring整合Hibernate --> <!-- 引入Hibernate的配置的信息=============== --> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <!-- 注入连接池 --> <property name="dataSource" ref="dataSource"/> <!-- 配置Hibernate的相关属性 --> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> <!-- 设置映射文件 --> <property name="mappingResources"> <list> <value>com/itzhouq/domain/Customer.hbm.xml</value> </list> </property> </bean>

9.3 Spring的配置文件最终版

删除Hibernate的配置文件

最终Spring的配置文件如下:

<?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"> <!-- 引入外部属性文件=============================== --> <context:property-placeholder location="classpath:jdbc.properties"/> <!-- 配置C3P0连接池=============================== --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driverClass}"/> <property name="jdbcUrl" value="${jdbc.url}"/> <property name="user" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!-- Spring整合Hibernate --> <!-- 引入Hibernate的配置的信息=============== --> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <!-- 注入连接池 --> <property name="dataSource" ref="dataSource"/> <!-- 配置Hibernate的相关属性 --> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> <!-- 设置映射文件 --> <property name="mappingResources"> <list> <value>com/itzhouq/domain/Customer.hbm.xml</value> </list> </property> </bean> <!-- 配置Dao --> <bean id="customerDao" class="com.itzhouq.dao.impl.CustomerDaoImpl"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!-- 配置Action============= --> <bean id="customerAction" class="com.itzhouq.web.action.CustomerAction" scope="prototype" > <!-- 手动注入Service --> <property name="customerService" ref="customerService"/> </bean> <!-- 配置Service================ --> <bean id="customerService" class="com.itzhouq.service.impl.CustomerServiceImpl"> <property name="customerDao" ref="customerDao"></property> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!-- 开启注解事务 --> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>

转载于:https://www.cnblogs.com/itzhouq/p/ssh1.html

最新回复(0)