SSH---整合Struts2&Spring&Hibernate(实例)
一.SSH回顾
Struts2:核心为过滤器+拦截器。过程:Filter--->FilterDispatcher-->ActionMapper-->ActionProxy-->ActionInvocation-->各种拦截器。
Struts2初用无需过于执著细节,我们只需要知道,它就是用来负责处理请求!在原生Servlet、Serviec、Dao中,它负责Servlet的工作!
Spring:核心为IOC+DI+AOP。原理细节复杂,但道理和目的很明确简单!它的功能就是2个:1)方便地创建对象;2)方便加功能!
Hibernate:核心为通过配置各种映射关系,将Dao层操作,从操作数据库表格转换为操作java对象!它就是封装了JDBC操作数据库那一套操作!
作为初学,必须掌握它们的核心。操作问题必须通过多敲代码熟练并体会。
二、整合Struts2&Spring&Hibernate(实例)
本例目的:用SSH完成往数据库插入数据。
过程说明:在本例当中,用Sturts2的Action类处理请求,调用service处理;在dao层,利用Spring做的 Hibernate模板完成数据库操作;而各个类之间的对象创建,利用Spring的IOC和DI完成,简单来说,就是只在类中声名该对象,创建什么的工作,我们只负责配置即可!
结构说明:本例将源码列出,直接从源码体会,部分代码给出注释。
1 环境准备
jar包:过多,略。后期指望Maven完成
数据库:
CREATE TABLE `bbb` ( `id` int(11) NOT NULL AUTO_INCREMENT, `category` varchar(100) DEFAULT NULL, PRIMARY KEY (`id`) )
2 源码
1)持久类对象:bean对象
1 package gaga.bean; 2 3 4 import javax.persistence.*; 5 6 /** 7 * @author Vincent 8 * @Description: 9 * @create 2018-02-05 20:15 10 */ 11 @Entity 12 @Table(name = "bbb", schema = "spring") 13 public class BbbEntity { 14 @Id 15 @Column(name = "id") 16 private int id; 17 18 @Column(name = "category") 19 private String category; 20 21 22 public int getId() { 23 return id; 24 } 25 26 public void setId(int id) { 27 this.id = id; 28 } 29 30 31 public String getCategory() { 32 return category; 33 } 34 35 public void setCategory(String category) { 36 this.category = category; 37 } 38 39 @Override 40 public String toString() { 41 return "BbbEntity{" + 42 "id=" + id + 43 ", category='" + category + '\'' + 44 '}'; 45 } 46 }
2)Action类
1 package gaga.test; 2 3 import com.opensymphony.xwork2.ActionSupport; 4 import gaga.bean.BbbEntity; 5 import gaga.service.UserService; 6 import org.springframework.context.annotation.Scope; 7 import org.springframework.stereotype.Controller; 8 9 import javax.annotation.Resource; 10 11 12 /** 13 * @author Vincent 14 * @Description: 15 * @create 2018-02-05 15:18 16 */ 17 @Scope("prototype") 18 @Controller 19 public class ActionDemo extends ActionSupport { 20 21 @Resource(name = "us") 22 private UserService userService; 23 24 /** 25 * 在Dao层保存数据,保存对象遗留到dao层直接创建处理 26 * 27 * @return 28 */ 29 public String save() { 30 System.out.println("ActionDemo#save......"); 31 userService.save(); 32 return NONE; 33 } 34 35 /** 36 * 懒加载查询数据,条件遗留在dao层处理 37 * 38 * @return 39 */ 40 public String loadSave() { 41 System.out.println("Action#loadSave......"); 42 BbbEntity bbbEntity = userService.loadSave(); 43 System.out.println("loadSave result--->" + bbbEntity); 44 return NONE; 45 } 46 }
3)Service接口
1 package gaga.service; 2 3 import gaga.bean.BbbEntity; 4 5 /** 6 * @author Vincent 7 * @Description: 8 * @create 2018-02-05 16:02 9 */ 10 public interface UserService { 11 void save(); 12 13 BbbEntity loadSave(); 14 }
4)Service接口实现类
1 package gaga.service.serviceImpl; 2 3 import gaga.bean.BbbEntity; 4 import gaga.dao.UserDao; 5 import gaga.service.UserService; 6 import org.springframework.stereotype.Service; 7 import org.springframework.transaction.annotation.Transactional; 8 9 import javax.annotation.Resource; 10 11 /** 12 * @author Vincent 13 * @Description: 14 * @create 2018-02-05 16:03 15 */ 16 @Transactional 17 @Service("us") 18 public class UserServiceImpl implements UserService { 19 20 @Resource(name = "userDao") 21 private UserDao userDao; 22 23 @Override 24 public void save() { 25 System.out.println("UserServiceImpl#save...."); 26 userDao.save(); 27 28 } 29 30 @Override 31 public BbbEntity loadSave() { 32 return userDao.loadSave(); 33 } 34 }
5)Dao接口
1 package gaga.dao; 2 3 import gaga.bean.BbbEntity; 4 5 /** 6 * @author Vincent 7 * @Description: 8 * @create 2018-02-05 16:06 9 */ 10 public interface UserDao { 11 void save(); 12 13 BbbEntity loadSave(); 14 }
6)Dao接口实现类
1 package gaga.dao.UserDaoImpl; 2 3 import gaga.bean.BbbEntity; 4 import gaga.dao.UserDao; 5 import org.springframework.orm.hibernate5.support.HibernateDaoSupport; 6 7 8 /** 9 * @author Vincent 10 * @Description: 11 * @create 2018-02-05 16:09 12 */ 13 14 public class UserDaoImpl extends HibernateDaoSupport implements UserDao { 15 16 @Override 17 public void save() { 18 System.out.println("UserDaoImpl#save....."); 19 20 BbbEntity user = new BbbEntity(); 21 user.setCategory("eeeeee"); 22 23 getHibernateTemplate().save(user); 24 25 } 26 27 @Override 28 public BbbEntity loadSave() { 29 System.out.println("UserDaoImpl#loadSave"); 30 BbbEntity load = getHibernateTemplate().load(BbbEntity.class, 60); 31 32 return load; 33 } 34 }
7)jdbc.properties(抽取出来,方便维护)
driverClass=com.mysql.jdbc.Driver jdbcUrl=jdbc:mysql:///spring user=root password=123
8)log4j.properties(日志处理配置)
##\u8BBE\u7F6E\u65E5\u5FD7\u8BB0\u5F55\u5230\u63A7\u5236\u53F0\u7684\u65B9\u5F0F log4j.appender.s=org.apache.log4j.ConsoleAppender log4j.appender.s.Target=System.err log4j.appender.s.layout=org.apache.log4j.PatternLayout log4j.appender.s.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c{1}:%L - %m%n ##\u8BBE\u7F6E\u65E5\u5FD7\u8BB0\u5F55\u5230\u6587\u4EF6\u7684\u65B9\u5F0F log4j.appender.file=org.apache.log4j.FileAppender log4j.appender.file.File=mylog.log log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c{1}:%L - %m%n ##\u65E5\u5FD7\u8F93\u51FA\u7684\u7EA7\u522B\uFF0C\u4EE5\u53CA\u914D\u7F6E\u8BB0\u5F55\u65B9\u6848 log4j.rootLogger=info, s, file
9)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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd "> <context:component-scan base-package="gaga"/> <bean id="userDao" class="gaga.dao.UserDaoImpl.UserDaoImpl"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</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="packagesToScan" value="gaga.bean"/> </bean> <context:property-placeholder location="classpath:jdbc.properties"/> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${driverClass}"/> <property name="jdbcUrl" value="${jdbcUrl}"/> <property name="user" value="${user}"/> <property name="password" value="${password}"/> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
10)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> <package name="struts2" namespace="/" extends="struts-default"> <action name="user_*" class="actionDemo" method="{1}"></action> </package> </struts>
11)web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <listener> <!--监听项目启动,即初始化applicationContext配置文件--> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- 这个过滤器,必须放在struts的过滤器的前面配置:配置处理懒加载问题 --> <filter> <filter-name>openSession</filter-name> <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>openSession</filter-name> <url-pattern>*.action</url-pattern> </filter-mapping> <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> </web-app>
3. 运行结果
访问:http://localhost:8080/user_save
访问成功,数据库插入一条数据
访问:http://localhost:8080/user_loadSave.action.loadSave
访问成功,成功过查出id为64的结果:result--->BbbEntity{id=64, category='eeeeee'}