搭建的环境:eclispe下面的maven web项目
Struts: 2.5.10
Spring: 4.3.8
Hibernate: 5.1.7 .Final
MySQL: 5.1.30
先来详细的讲解一下SSH框架的整合,在这里是将struts2.0的Action的创建工作由Spring进行统一管理,主要是利用了Spring
控制反转和依赖注入的功能。
而将hibernate.cfg.xml整合Spring的配置文件中。而且利用Spring的面向切向功能对Hibernate事务进行统一管理。给实体类添加注解,表明了与表之间的映射关系,将Hibernate中的SessionFactory配置到了Spring的配置文件下面。就是注入连接池。
项目的结构:
Pom.xml文件:
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 3 <modelVersion>4.0.0</modelVersion> 4 <groupId>cn.test.book</groupId> 5 <artifactId>SSHproject</artifactId> 6 <packaging>war</packaging> 7 <version>0.0.1-SNAPSHOT</version> 8 <name>SSHproject Maven Webapp</name> 9 <url>http://maven.apache.org</url> 10 <properties> 11 <!-- 统一源码的编码方式 --> 12 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 13 <!-- 统一各个框架版本 --> 14 <struts.version>2.5.10</struts.version> 15 <spring.version>4.3.8.RELEASE</spring.version> 16 <hibernate.version>5.1.7.Final</hibernate.version> 17 </properties> 18 19 20 <dependencies> 21 <dependency> 22 <groupId>junit</groupId> 23 <artifactId>junit</artifactId> 24 <version>3.8.1</version> 25 <scope>test</scope> 26 </dependency> 27 <dependency> 28 <groupId>javax</groupId> 29 <artifactId>javaee-api</artifactId> 30 <version>7.0</version> 31 </dependency> 32 33 34 35 <!-- Spring整合ORM框架依赖 --> 36 <dependency> 37 <groupId>org.springframework</groupId> 38 <artifactId>spring-orm</artifactId> 39 <version>${spring.version}</version> 40 </dependency> 41 42 43 <!-- Spring 核心依赖 --> 44 <dependency> 45 <groupId>org.springframework</groupId> 46 <artifactId>spring-core</artifactId> 47 <version>${spring.version}</version> 48 </dependency> 49 <!-- Spring web依赖 --> 50 <dependency> 51 <groupId>org.springframework</groupId> 52 <artifactId>spring-web</artifactId> 53 <version>${spring.version}</version> 54 </dependency> 55 <!-- Struts2 核心依赖 --> 56 <dependency> 57 <groupId>org.apache.struts</groupId> 58 <artifactId>struts2-core</artifactId> 59 <version>${struts.version}</version> 60 </dependency> 61 <!-- Struts2和Spring整合依赖 --> 62 <dependency> 63 <groupId>org.apache.struts</groupId> 64 <artifactId>struts2-spring-plugin</artifactId> 65 <version>${struts.version}</version> 66 </dependency> 67 68 <!-- Hibernate 核心依赖 --> 69 <dependency> 70 <groupId>org.hibernate</groupId> 71 <artifactId>hibernate-core</artifactId> 72 <version>${hibernate.version}</version> 73 </dependency> 74 75 76 <!-- MySQL 依赖 --> 77 <dependency> 78 <groupId>mysql</groupId> 79 <artifactId>mysql-connector-java</artifactId> 80 <version>5.1.30</version> 81 </dependency> 82 <!-- C3P0 依赖 --> 83 <dependency> 84 <groupId>com.mchange</groupId> 85 <artifactId>c3p0</artifactId> 86 <version>0.9.5</version> 87 </dependency> 88 <!-- AspectJ依赖 --> 89 <dependency> 90 <groupId>org.aspectj</groupId> 91 <artifactId>aspectjweaver</artifactId> 92 <version>1.8.10</version> 93 </dependency> 94 <!-- SLF4J依赖 --> 95 <dependency> 96 <groupId>org.slf4j</groupId> 97 <artifactId>slf4j-log4j12</artifactId> 98 <version>1.7.25</version> 99 </dependency> 100 101 102 </dependencies> 103 104 105 106 <build> 107 <finalName>SSHproject</finalName> 108 <plugins> 109 <!-- 统一源代码编译输出的JDK版本 --> 110 <!-- 这里我不能进行统一源代码输出版本JDK版本,容易出现错误 --> 111 <!-- <plugin> 112 <groupId>org.apache.maven.plugins</groupId> 113 <artifactId>maven-compiler-plugin</artifactId> 114 <version>3.5.1</version> 115 <configuration> 116 <source>1.7</source> 117 <target>1.7</target> 118 </configuration> 119 </plugin> --> 120 <!-- 打包时跳过单元测试 --> 121 <plugin> 122 <groupId>org.apache.maven.plugins</groupId> 123 <artifactId>maven-surefire-plugin</artifactId> 124 <version>2.19.1</version> 125 <configuration> 126 <skipTests>true</skipTests> 127 </configuration> 128 </plugin> 129 <!-- 集成Tomcat插件 --> 130 <plugin> 131 <groupId>org.apache.tomcat.maven</groupId> 132 <artifactId>tomcat7-maven-plugin</artifactId> 133 <version>2.2</version> 134 <configuration> 135 <path>/${project.artifactId}</path> 136 </configuration> 137 </plugin> 138 </plugins> 139 </build> 140 <!-- <build> 141 <finalName>SSHproject</finalName> 142 </build> --> 143 144 </project>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" 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" version="3.0"> <!-- 配置Struts2过滤器 --> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 配置Spring的监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 指定Spring配置文件所在路径 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> </web-app>
jdbc.properties
jdbc.url=jdbc:mysql:///mybatis?useSSL=true&characterEncoding=UTF-8 jdbc.driverClass=com.mysql.jdbc.Driver jdbc.username=root jdbc.password=
login4j.properties
log4j.rootCategory=INFO, console log4j.appender.console=org.apache.log4j.ConsoleAppender log4j.appender.console.layout=org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %5p %t %c{2}:%L - %m%n
messeageResource.properties
invalid.fieldvalue.price = \u5546\u54c1\u4ef7\u683c\u8f93\u5165\u683c\u5f0f\u6709\u8bef
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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" 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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- 开启包扫描,并注册注解 --> <context:component-scan base-package="cn.hncu.*"/> <!-- 引入属性文件 --> <context:property-placeholder location="classpath:jdbc.properties"/> <!-- 配置C3P0连接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <!-- 数据库连接相关信息 --> <property name="jdbcUrl" value="${jdbc.url}"/> <property name="driverClass" value="${jdbc.driverClass}"/> <property name="user" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!-- 配置Hibernate的SessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <!-- 注入连接池 --> <property name="dataSource" ref="dataSource"/> <!-- 配置Hibernate属性 --> <property name="hibernateProperties"> <props> <prop key="hibernate.show_sql">true</prop><!-- 是否展示SQL --> <prop key="hibernate.hbm2ddl.auto">update</prop><!-- 是否自动创建表结构 --> <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop> </props> </property> <!-- 扫描并加载注解过的实体类 --> <property name="packagesToScan" value="cn.hncu.domain"/> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <!-- 注入SessionFactory --> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!-- 配置事务增强 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- 配置需要进行事务管理的方法,和事务传播行为 --> <tx:method name="save*" propagation="REQUIRED"/> <tx:method name="update*" propagation="REQUIRED"/> <tx:method name="delete*" propagation="REQUIRED"/> </tx:attributes> </tx:advice> <bean id="productAction" class="cn.hncu.active.ProductAction"></bean><!--这个地方我可以不配,但是配上也不会出错,其实不配也行,因为下面采用了自动扫描注解了,在Spring里面采用自动扫描注解bean实体类的时候,就把struts.xml中的class改为了productAction如果采用@Controller未指定名称,就默认将类名的首字母小写--> <!-- 配置切面 --> <aop:config> <!-- 配置切入点 * cn.hncu.service.*+.*(..) *:表示方法的作用域,*表示所有 cn.hncu.service.*:表示org.ssh.service下的任何包 cn.hncu.service.*+:表示org.ssh.service下的任何包及其子包 *(..):*表示任何方法,(..)表示方法的任何参数 --> <aop:pointcut id="pointcut" expression="execution(* cn.hncu.service.*+.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/> </aop:config> </beans>
struts.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd"> <struts> <!-- 默认访问页面 --> <package name="default" extends="struts-default" namespace="/"> <default-action-ref name="default"/> <action name="default"> <result>/WEB-INF/view/index.jsp</result> </action> </package> <!-- 商品相关请求转发 --> <!-- Struts2在2.5版本后添加strict-method-invocation(严格方法访问),默认为true,不能使用动态方法调用功能,故需设为false --> <package name="product" extends="struts-default" namespace="/" strict-method-invocation="false"> <!-- 保存商品 --> <action name="product_*" class="productAction" method="{1}Product"> <result>WEB-INF/view/succ.jsp</result> <result name="input">WEB-INF/view/succ.jsp</result> </action> <!-- <action name="product_save" class="productAction" method="saveProduct"> <result name="success">/view/succ.jsp</result> </action> --> </package> <!-- 引入资源文件 --> <constant name="struts.custom.i18n.resources" value="messageResource"></constant> </struts>
Product.java
package cn.hncu.domain; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import org.hibernate.annotations.GenericGenerator; @Entity public class Product { @Id @GeneratedValue(generator = "id") @GenericGenerator(name = "id", strategy = "native") private Integer id;//商品ID @Column(length=100) private String pname;//商品名称 private double price;//商品价格 public Product() { } public Product(String pname, double price) { this.pname = pname; this.price = price; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getPname() { return pname; } public void setPname(String pname) { this.pname = pname; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } @Override public String toString() { return "Product [id=" + id + ", pname=" + pname + ", price=" + price + "]"; } }
productDao.java
package cn.hncu.dao; import cn.hncu.domain.Product; public interface ProductDao { void saveProduct(Product product); }
ProductDaoImpl.java
package cn.hncu.dao.Impl; import org.hibernate.SessionFactory; import org.springframework.orm.hibernate5.HibernateTemplate; import org.springframework.stereotype.Repository; import cn.hncu.dao.ProductDao; import cn.hncu.domain.Product; /** * 商品信息-服务层实现 * @author Administrator * */ @Repository public class ProductDaoImpl implements ProductDao{ private HibernateTemplate template; public ProductDaoImpl(SessionFactory sessionFactory) { this.template=new HibernateTemplate(sessionFactory); } @Override public void saveProduct(Product product) { System.out.println("调用到这里来了吗。。。。"); System.out.println("product=="+product); System.out.println("template=="+template); template.save(product); } }
ProductService.java
package cn.hncu.service; import cn.hncu.domain.Product; /* * 商品操作-服务层接口 * */ public interface ProductService { void saveProduct(Product product); }
ProductServiceImpl.java
package cn.hncu.service.Impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import cn.hncu.dao.ProductDao; import cn.hncu.domain.Product; import cn.hncu.service.ProductService; @Service public class ProductServiceImpl implements ProductService{ @Autowired private ProductDao productDao; @Override public void saveProduct(Product product) { System.out.println("调用到serviceImpl层来了吗?"); productDao.saveProduct(product); } }
index.jsp
package cn.hncu.service.Impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import cn.hncu.dao.ProductDao; import cn.hncu.domain.Product; import cn.hncu.service.ProductService; @Service public class ProductServiceImpl implements ProductService{ @Autowired private ProductDao productDao; @Override public void saveProduct(Product product) { System.out.println("调用到serviceImpl层来了吗?"); productDao.saveProduct(product); } }
succ.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Insert title here</title> </head> <body> 恭喜你成功保存!! </body> </html>
最后在这里我讲一下我在这里遇到过的问题以及解决方法吧,在struts2中默认是多实例(Prototype),每个请求都会产生相应的action实例去处理,但是spring整合之后,就由Spring管理bean,默认是单例模式,Action继承actionSupport会检验数据,如果转换出错,会找到你要input视图。没配就出错找不到。但是继续访问该action还是会报错,因为是单例,上次的异常还在,因为没有清除,所以继续出错返回input可以给action加上@Scope(”prototype")singleton单例模式