这里整合的是struts2 + spring + hibernate框架,只是简单的整合。
项目工程的结构如下:
下面是使用的pom文件。
<properties> <!-- 统一源码的编码方式 --> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <!-- 统一各个框架版本 --> <struts.version>2.5.10</struts.version> <spring.version>4.3.8.RELEASE</spring.version> <hibernate.version>5.1.7.Final</hibernate.version> </properties> <dependencies> <!-- Junit依赖 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!-- Spring 核心依赖 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <!-- Spring web依赖 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <!-- Spring整合ORM框架依赖 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <!-- Struts2 核心依赖 --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>${struts.version}</version> </dependency> <!-- Struts2和Spring整合依赖 --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-spring-plugin</artifactId> <version>${struts.version}</version> </dependency> <!-- Hibernate 核心依赖 --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <!-- MySQL 依赖 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.42</version> </dependency> <!-- HikariCP 依赖 --> <dependency> <groupId>com.zaxxer</groupId> <artifactId>HikariCP</artifactId> <version>2.7.4</version> </dependency> <!-- AspectJ依赖 --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.10</version> </dependency> <!-- SLF4J依赖 --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.25</version> </dependency> </dependencies> </project>
第一部分,整合hibernate和spring
首先创建一个hibernate.cfg.xml配置文件,因为整合后,需要将sessionFactory交给spring来管理。所以这里只写了hibernate的基本配置。
<!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> <!-- 配置Hibernate的基本属性 --> <!-- 1.数据源配置到IOC容器中 --> <!-- 2.关联的.hbm.xml也在IOC容器配置SessionFactory实例 --> <!-- 3.配置Hibernate的基本属性:方言,SQL显示及格式化,生成数据表的策略以及二级缓存 --> <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property> <!-- 是否显示格式化SQL --> <property name="hibernate.show_sql">true</property> <property name="hibernate.format_sql">true</property> <!-- 生成数据表的策略 --> <property name="hbm2ddl.auto">update</property> </session-factory> </hibernate-configuration>
接下来创建spring的管理容器的applicationContext.xml。在这里配置数据源,hibernate配置文件的路径,以及实体类的映射文件路径。
同时配置hibernate的事务管理器。
<bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="jdbcUrl" value="jdbc:mysql://localhost/bookstore?useSSL=true" /> <property name="username" value="root"></property> <property name="password" value="123456"></property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" lazy-init="false"> <!-- 注入datasource,给sessionfactoryBean内setdatasource提供数据源 --> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:hibernate.cfg.xml"></property> <!-- 加载实体类的映射文件位置及名称 --> <property name="mappingLocations" value="classpath:com/mrlv/pojo/*.hbm.xml"></property> </bean> <!-- 配置 spring 的声明式事务 --> <!-- 1.配置habernate的事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 2.配置事务的属性 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="find*" read-only="true"/> <tx:method name="*"/> </tx:attributes> </tx:advice> <!-- 3.配置事务的切入点,再把事务属性和事务切入点关联起来,这里切入的目录是com.mrlv.service包下的所有类及其子包下的类的所有方法 --> <aop:config> <aop:pointcut expression="execution(* com.mrlv.service..*.*(..))" id="txPointcut"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/> </aop:config>
之后,在dao类中调用sessionFactory。这里采用的是注解的方式。
@Repository public class BookDaoImpl implements BookDao { @Resource private SessionFactory sessionFactory; //获取和当前线程绑定的Seesion private Session getSession() { return this.sessionFactory.getCurrentSession(); } @Override public BookResult findAll(BookResult result) { if(result == null) { result = new BookResult(); } //分页查询 StringBuilder sql = new StringBuilder("from Book b left join fetch b.booktype bt"); if(result.getBname() != null && !"".equals(result.getBname().trim())) { sql.append(" where bname like ‘%" + result.getBname() + "%‘"); } if(result.getTypeid() != null && 0!=result.getTypeid()) { if(sql.indexOf("where") == -1) { sql.append(" where bt.id=" + result.getTypeid()); } else { sql.append(" and bt.id=" + result.getTypeid()); } } if(result.getBpriceStart() != null && 0!=result.getBpriceStart()) { if(sql.indexOf("where") == -1) { sql.append(" where b.bprice>" + result.getBpriceStart()); } else { sql.append(" and b.bprice>" + result.getBpriceStart()); } } if(result.getBpriceEnd() != null && 0!=result.getBpriceEnd()) { if(sql.indexOf("where") == -1) { sql.append(" where b.bprice<" + result.getBpriceEnd()); } else { sql.append(" and b.bprice<" + result.getBpriceEnd()); } } List<Book> books = getSession().createQuery(sql.toString()) .setFirstResult(result.getBegin()) .setMaxResults(result.getPageSize()).list(); //查询总页数,注意,这里直接使用sql会报错,因为fetch和count(*)不能共存,所以需要删去fetch。 String sqlcount = sql.toString().replaceAll("fetch", ""); Long rows = (Long) getSession().createQuery( "select count(*) " + sqlcount). uniqueResult(); result.setRows(rows.intValue()); result.setList(books); return result; } }
如此,便完成了spring和hibernate的整合。可以先用test方法调试。
第二部分,整合struts2和spring
整合struts2和spring的要点。将action交给spring管理。
首先,配置web.xml文件。添加struts2过滤器,然后加载spring的配置文件applictionContext.xml。以及添加spring监听器。
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> <!-- 添加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> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> </web-app>
然后创建Action,注意,这里采用注解方式@Controller,这里的Action的创建方式需要采用多例。所以需要添加@Scope("prototype")。这样就将Action交由spring来管理。
package com.mrlv.action; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import com.mrlv.pojo.Book; import com.mrlv.pojo.BookType; import com.mrlv.result.BookResult; import com.mrlv.service.BookService; import com.mrlv.service.BookTypeService; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.util.ValueStack; @Controller @Scope("prototype") public class BookAction extends ActionSupport{ /** * */ private static final long serialVersionUID = 1L; @Resource private BookService bookService; @Resource private BookTypeService bookTypeService; private BookResult result; public String execute() throws Exception { ActionContext context = ActionContext.getContext(); ValueStack valueStack = context.getValueStack(); System.out.println("进入BookAction"); result = bookService.findAll(result); List<BookType> types = bookTypeService.findAll(); valueStack.set("result", result); valueStack.set("types", types); System.out.println(result); return SUCCESS; } public BookResult getResult() { return result; } public void setResult(BookResult result) { this.result = result; } }
接下来编写struts.xml文件。这里的calss写的是bookAction。是因为spring容器生产实体对象默认是首字母小写。
<?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="book" extends="struts-default" namespace="/"> <action name="list" class="bookAction"> <result name="success">/WEB-INF/listBook.jsp</result> </action> </package> </struts>
如此便是将ssh框架简单整合完毕
原文地址:https://www.cnblogs.com/lvshiyu/p/8179913.html
时间: 2024-10-11 22:34:07