S2SH框架整合XML版(九)

    xiaoxiao2022-07-13  156

    爱一个人是一回事,拥有一个人是另外一回事,爱上并拥有一个人,更是另外一回事。 蝴蝶,是什么,是希望,是真正的希望。

    上一章简单介绍了Spring的事务配置(八),如果没有看过,请观看上一章。

    一. S2SH 框架整合

    S2SH 指的是 Struts2, Spring,Hibernate三大框架,重要性什么的都不说了,都明白。 在学习本章之前,建议先将Struts2 与Hibernate 学习一下,可参考以前的文章。 整合的思路,是两两整合。 Struts2与Spring 整合, Spring 与Hibernate 整合。

    二. Struts2 与Spring 整合

    二.一 Struts2 的jar 包

    有基本的包: 有关于json 操作的包: 有与Spring 结合的包:

    二.二. Spring 的jar 包

    spring 的基本的包 与aop 有关的包 与jdbc和事务有关的包 有与web 整合的包 其中,还有一个与orm 整合的包,后面会讲到的。

    将上面的这些jar 包,放置到WEB-INF 下面的lib 文件夹下,并添加到类路径下。 其中,有两个jar包重复了。 commons-logging-1.1.3.jar (struts2的json) 与 commons-logging-1.2.jar (spring) 去除掉低版本的1.1.3, 剩下1.2.jar 包。

    二.三. 基本环境搭建

    pojo 包下的User类 package com.yjl.pojo; /** @author:yuejl @date: 2019年4月20日 上午10:06:22 @Description 类的相关描述 */ public class User { /** * @param id 主键编号 * @param name 姓名 * @param sex 性别 * @param age 年龄 */ private Integer id; private String name; private String sex; private Integer age; public User() { super(); } public User(Integer id, String name, String sex, Integer age) { super(); this.id = id; this.name = name; this.sex = sex; this.age = age; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "User [id=" + id + ", name=" + name + ", sex=" + sex + ", age=" + age+"]"; } } dao包下面的UserDao 接口。 package com.yjl.dao; import java.util.List; import com.yjl.pojo.User; /** @author:yuejl @date: 2019年5月22日 下午8:04:06 @Description 类的相关描述 */ public interface UserDao { public List<User> findAll(); } dao包impl 子包下面的UserDaoImpl 类 package com.yjl.dao.impl; import java.util.ArrayList; import java.util.List; import org.springframework.orm.hibernate5.HibernateTemplate; import com.yjl.dao.UserDao; import com.yjl.pojo.User; /** @author:yuejl @date: 2019年5月22日 下午8:04:43 @Description 类的相关描述 */ public class UserDaoImpl implements UserDao { @Override public List<User> findAll() { System.out.println("执行了查询全部的方法"); List<User> userList=new ArrayList<User>(); // 先进行实现化取出,不与Hibernate 进行整合。 User user1=new User(); user1.setName("两个蝴蝶飞"); user1.setId(1); user1.setSex("男"); user1.setAge(24); userList.add(user1); return userList; } } service 包下的UserService 接口 package com.yjl.service; import java.util.List; import com.yjl.pojo.User; /** @author:yuejl @date: 2019年5月22日 下午8:04:57 @Description 类的相关描述 */ public interface UserService { public List<User> findAll(); } service 包的impl 包下的UserServiceImpl 类 package com.yjl.service.impl; import java.util.List; import com.yjl.dao.UserDao; import com.yjl.pojo.User; import com.yjl.service.UserService; /** @author:yuejl @date: 2019年5月22日 下午8:05:15 @Description 类的相关描述 */ public class UserServiceImpl implements UserService { // 放置dao 层的引用。 private UserDao userDao; @Override public List<User> findAll() { return userDao.findAll(); } public UserDao getUserDao() { return userDao; } public void setUserDao(UserDao userDao) { this.userDao = userDao; } } web.action 包下的UserAction 控制类 package com.yjl.web.action; import java.util.List; import com.opensymphony.xwork2.ActionContext; import com.yjl.pojo.User; import com.yjl.service.UserService; /** @author:yuejl @date: 2019年5月22日 下午8:05:24 @Description 类的相关描述 */ public class UserAction { private UserService userService; public String list(){ List<User> userList=userService.findAll(); ActionContext.getContext().getValueStack(). set("userList", userList); return "list"; } public UserService getUserService() { return userService; } public void setUserService(UserService userService) { this.userService = userService; } } 当然,不要忘记放置配置文件。在config(源文件夹) 下放置配置文件 applicationContext.xml ,struts.xml,log4j.properties 前端展示页面 list.jsp 进行数据的展示。 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="/struts-tags" prefix="s"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="stylesheet" href="${pageContext.request.contextPath}/JS/bootstrap/css/bootstrap.min.css" type="text/css"/> <script type="text/javascript" src="${pageContext.request.contextPath}/JS/bootstrap/js/bootstrap.min.js"></script> <title>显示列表信息</title> </head> <body> <div class="container"> <div class="row"> <table class="table table-bordered table-hover"> <caption>查看用户信息</caption> <thead> <tr> <th class="col-xs-2">姓名</th> <th class="col-xs-2">性别</th> <th class="col-xs-2">年龄</th> <th class="col-xs-4" colspan="3">相关操作 <span style="padding-left:40px"> <a href="#">添加按钮</a> </span> </th> </tr> </thead> <tbody> <s:iterator value="userList" var="user"> <tr> <td>${user.name}</td> <td>${user.sex}</td> <td>${user.age}</td> <td> <a href="#">查看详情</a>       <a href="#">修改</a>       <a href="#">删除</a> </tr> </s:iterator> </tbody> </table> </div> </div> </body> </html>

    二.四 web.xml 文件的配置

    主要分为三个部分,一个是配置spring 启动时的监听器,一个是配置启动参数,指定spring配置文件的位置,另外一个是配置struts2的过滤器。

    <?xml version="1.0" encoding="UTF-8"?> <!--为2.5 版本--> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>SSH整合</display-name> <!-- 配置spring 启动时的监听器 --> <listener> <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> <!-- 配置struts2的过滤器 --> <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> <!--欢迎页面--> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> </web-app>

    二.五 applicationContext.xml 配置

    主要有两方面的作用,一个是添加spring的众多约束。 一个是xml 方式配置bean. 注意,UserAction 类是prototype ,多例的。

    <?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"> <!-- 设置userDao类 --> <bean id="userDao" class="com.yjl.dao.impl.UserDaoImpl"> </bean> <!-- 设置userService --> <bean id="userService" class="com.yjl.service.impl.UserServiceImpl"> <property name="userDao" ref="userDao"></property> </bean> <!-- 设置userAction --> <bean id="userAction" class="com.yjl.web.action.UserAction" scope="prototype"> <property name="userService" ref="userService"></property> </bean>

    二.六 struts2.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> <!--修改国际化编码 --> <constant name="struts.i18n.encoding" value="UTF-8"></constant> <!--修改是否为开发者模式 --> <constant name="struts.enable.devMode" value="true"></constant> <package name="user" extends="struts-default" namespace="/"> <action name="User_*" class="userAction" method="{1}"> <result name="list">list.jsp</result> </action> </package> </struts>

    二.七 启动服务器,验证一下struts2与spring的整合

    说明,Spring与Struts2整合成功。 接下来,是Spring与Hibernate进行整合。

    三. Spring与Hibernate 进行整合(牵扯到数据库)

    这两个整合,主要是将Hibernate的SessionFactory 的创建交给Spring,事务管理也交给Spring。 在dao层中引入HibernateTemplate 类进行。

    三.一 Hibernate的jar包

    基本包: c3p0 连接池包 hibernate的日志包

    三.二 mysql 驱动包

    三.三 Spring的orm 包(去spring中找)

    有重复的jar包。 javassist-3.11.0.GA.jar (struts2里面) 与 javassist-3.22.0-GA.jar (hibernate 里面) 去掉低版本的。

    三.四 配置Hibernate的User.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 package="com.yjl.pojo"> <!-- 具体的实体类 --> <class name="User" table="user"> <!-- 主键 --> <id name="id" column="id"> <generator class="native"></generator> </id> <!-- 其余属性 --> <property name="name"></property> <property name="sex" ></property> <property name="age"></property> </class> </hibernate-mapping>

    三.五 配置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> <!-- 关于Hibernate的相应配置移动到Spring了。 --> <!-- 引入方言 --> <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.hbm2ddl.auto">update</property> <property name="hibernate.format_sql">true</property> <!-- 引入相应的约束文件 ctrl点击时可以正确进入--> <mapping resource="com/yjl/pojo/User.hbm.xml"/> </session-factory> </hibernate-configuration>

    三.六 jdbc.properites 文件

    jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/spring jdbc.username=root jdbc.password=abc123

    下面的一切,都是在applicationContext.xml 配置文件中进行的。

    三.七 配置数据源 ,采用c3p0的方式

    <!-- 引入配置文件 前面要加上classpath--> <context:property-placeholder location="classpath:jdbc.properties"/> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driverClassName}"/> <property name="jdbcUrl" value="${jdbc.url}"/> <property name="user" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean>

    三.八 创建SessionFactory

    <!-- 创建sessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <!--指定hibernate配置文件的位置--> <property name="configLocations" value="classpath:hibernate.cfg.xml"></property> </bean>

    三.九 创建HibernateTemplate

    <!-- 创建Hibernate模板 --> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate"> <property name="sessionFactory" ref="sessionFactory"></property> </bean>

    三.十 在userDao中引入hibernateTemplate

    需要将userDao与HibernateTempldate 类进行相应的关联,在UserDaoImpl 类中采用setter 注入的方式进行关联。 所以, userDaoImpl 便需要进行相应的修改:

    package com.yjl.dao.impl; import java.util.ArrayList; import java.util.List; import org.springframework.orm.hibernate5.HibernateTemplate; import com.yjl.dao.UserDao; import com.yjl.pojo.User; /** @author:yuejl @date: 2019年5月22日 下午8:04:43 @Description 类的相关描述 */ public class UserDaoImpl implements UserDao { private HibernateTemplate hibernateTemplate; @SuppressWarnings("unchecked") @Override public List<User> findAll() { System.out.println("执行了查询全部的方法"); List<User> userList=new ArrayList<User>(); // 采用hibernate查询的方式。 String hql="from User"; System.out.println("输出值为:"+hibernateTemplate); userList=(List<User>) hibernateTemplate.find(hql); return userList; } public HibernateTemplate getHibernateTemplate() { return hibernateTemplate; } public void setHibernateTemplate(HibernateTemplate hibernateTemplate) { this.hibernateTemplate = hibernateTemplate; } }

    需要改变一下 userDao 的bean 创建,setter注入hibernateTemplate 属性

    <!-- 设置userDao类 --> <bean id="userDao" class="com.yjl.dao.impl.UserDaoImpl"> <property name="hibernateTemplate" ref="hibernateTemplate"></property> </bean>

    三.十一 重启服务器,进行验证

    说明,Hibernate 查询OK, Spring 与Hibernate 简单整合成功。 但,还没有结束。

    三.十二 添加事务管理

    <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 配置事务 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!--列举常见的方法形式--> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="edit*" propagation="REQUIRED" /> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="new*" propagation="REQUIRED" /> <tx:method name="set*" propagation="REQUIRED" /> <tx:method name="remove*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="change*" propagation="REQUIRED" /> <tx:method name="get*" propagation="REQUIRED" read-only="true" /> <tx:method name="find*" propagation="REQUIRED" read-only="true" /> <tx:method name="count*" propagation="REQUIRED" read-only="true" /> <tx:method name="load*" propagation="REQUIRED" read-only="true" /> <tx:method name="*" propagation="REQUIRED" read-only="true" /> </tx:attributes> </tx:advice> <!-- 配置aop --> <aop:config> <aop:pointcut expression="execution( * com.yjl.service.impl.*.*(..))" id="pointCut1"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="pointCut1"/> </aop:config>

    三.十三 在web.xml 中添加Session延迟加载OpenSessionInViewFilter

    <filter> <filter-name>openSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class> <init-param> <param-name>singleSession</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>openSessionInViewFilter</filter-name> <url-pattern>*.action</url-pattern> </filter-mapping>

    三.十四 在web.xml 上配置编码过滤器(放在struts2前面)

    <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>

    至此,一个简单的S2SH 的整合便基本完成 了。 这只是xml 形式的,还有更简单的注解方式的。

    四.所用jar包

    共49个基本的。 谢谢!!!

    最新回复(0)