欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring整合Struts 2与Hibernate(基于XML配置的S2SH整合)

程序员文章站 2022-07-14 23:41:59
...

(1) 添加Hibernate框架及相关的jar包 。
可以从官方网站http://www.hibernate.org下载所需要的版本(这里以hibernate 5.2.6版本为例)。
解压刚下载的压缩包,解压缩得到一个名为hibernate-release-5.2.6.Final的文件夹,目录结构,如图所示。各个文件和文件夹的说明。
Spring整合Struts 2与Hibernate(基于XML配置的S2SH整合)
将hibernate-release-5.2.6.Final.zip解压后的lib\required目录下如图20-1所示的10个jar包,以及MySQL数据库驱动包mysql-connector-java-5.1.18-bin.jar、Hibernate事务管理包jboss-transaction-api_1.1_spec-1.0.1.Final.jar、连接池核心包c3p0-0.9.5.2.jar、c3p0连接池的依赖包mchange-commons-java-0.2.11.jar这4个包复制到项目s2sh的WebRoot\WEB-INF\lib目录中。
Spring整合Struts 2与Hibernate(基于XML配置的S2SH整合)
(2) 添加Spring框架及相关的jar包。
将spring-framework-4.3.5.RELEASE-dist.zip解压后libs目录下的如图20-2所示的12个jar包,以及相关的aopalliance-1.0.jar、aspectjweaver-1.8.6.jar和cglib-3.2.0.jar这3个jar包复制到项目s2sh的WebRoot\WEB-INF\lib目录中。
Spring整合Struts 2与Hibernate(基于XML配置的S2SH整合)
(3) 添加Struts 2框架的jar包 。
将struts-2.5.8-lib.zip解压后的lib目录下如图20-3所示的14个jar包复制到项目s2sh的WebRoot\WEB-INF\lib目录中。
项目最终的目录结构如图20-4所示。Spring整合Struts 2与Hibernate(基于XML配置的S2SH整合)
Spring整合Struts 2与Hibernate(基于XML配置的S2SH整合)
创建实体类及映射文件
(3) 创建实体类
在src目录下创建包com.restaurant.entity,在包中创建实体类Users,与数据库restrant中的数据表users对应。

 private Set orderses = new HashSet(0);//一对多关系写入

(4) 创建映射文件
在com.restaurant.entity包中创建与实体类Users对应的映射文件Users.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">
<!-- JavaBean所在包的全路径 -->
<hibernate-mapping package="com.restaurant.entity">
	<!-- 实体类和数据库表映射 -->
	<class name="Users" table="users" catalog="restrant">
		<id name="id" type="java.lang.Integer"><!-- 对应实体类中的属性 -->
			<column name="Id" /><!-- 对应数据库中的列 -->
			<generator class="native"></generator><!-- 主键的方式,根据本地数据库 -->
		</id>
		<property name="loginName" type="java.lang.String">
			<column name="LoginName" length="20" />
		</property>
		<property name="loginPwd" type="java.lang.String">
			<column name="LoginPwd" length="20" />
		</property>
		<property name="trueName" type="java.lang.String">
			<column name="TrueName" length="20" />
		</property>
		<property name="email" type="java.lang.String">
			<column name="Email" length="20" />
		</property>
		<property name="phone" type="java.lang.String">
			<column name="Phone" length="20" />
		</property>
		<property name="address" type="java.lang.String">
			<column name="Address" length="50" />
		</property>

		<property name="status" type="java.lang.Integer">
			<column name="Status" />
		</property>
		<!-- 配置一对多关联映射 -->
		<set name="orderses" inverse="true" lazy="false">
		<!-- 一对多则是反转控制(一般是多对一)inverse="true" -->
			<key>
				<column name="UserId" /><!-- 所关联数据库表的外键 -->
			</key>
			<one-to-many class="Orders" /><!-- 所关联的实体类 -->
		</set>
	</class>
</hibernate-mapping>
**Spring整合Hibernate-  >(applicationContext.xml)**
Spring整合Hibernate目的在于由Spring的IOC容器来管理Hibernate的SessionFactory,同时让Hibernate使用Spring的声明式事务,这些目的的实现是在Spring配置文件中完成的。
在src目录下创建Spring配置文件applicationContext.xml
基于XML配置数据源dataSource
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="com.mysql.jdbc.Driver" />
		<property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/restrant" />
		<property name="user" value="root" />
		<property name="password" value="root" />
		<property name="minPoolSize" value="5" />
		<property name="maxPoolSize" value="10" />
	</bean>

配置Hibernate的sessionFactory实例 ( 配置实体类映射文件 )

<bean id="sessionFactory"
		class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
		<property name="dataSource">
			<ref bean="dataSource" />
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">
					org.hibernate.dialect.MySQLDialect
				</prop>
			</props>
		</property>
		<property name="mappingResources">
			<list>
				<value>com/restaurantTest/entity/Users.hbm.xml</value>
				<value>com/restaurantTest/entity/Meal.hbm.xml</value>
				<value>com/restaurantTest/entity/Orders.hbm.xml</value>
				<value>com/restaurantTest/entity/Orderdts.hbm.xml</value>
				<value>com/restaurantTest/entity/Mealseries.hbm.xml</value>
			</list>
		</property>
	</bean>

声明Hibernate事务管理器、定义事务通知、定义切面,并将事务通知和切面组合

<!-- 声明Hibernate事务管理器 -->
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate5.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
	
	<!-- 定义事务通知 -->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="*" propagation="REQUIRED" />
		</tx:attributes>
	</tx:advice>
	
	<!--定义切面,并将事务通知和切面组合(定义哪些方法应用事务规则) -->
	<aop:config>
		<!-- 对com.restaurant.service包下的所有类的所有方法都应用事务规则 -->
		<aop:pointcut id="serviceMethods"
			expression="execution(* com.restaurantTest.service.*.*(..))" />
		<!-- 将事务通知和切面组合 -->
		<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethods" />
	</aop:config>

配置类实例(bean注入 scope=“prototype”)

.
DAO层开发
(5) 在项目s2sh中创建包com.resta
urant.dao,在包中创建接口UsersDAO,在UsersDAO接口中声明方法search,用于登录验证 。
(6) 创建UsersDAO接口的实现类UsersDAOImpl,存放在com.restaurant.dao.impl包中,实现search方法。

    public class BaseDaoImpl<T> implements BaseDAO<T>{

	private SessionFactory sessionFactory;
	
	
	
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public Session getCurrentSession(){
		return this.getSessionFactory().getCurrentSession();
	}
	
	@Override
	public Serializable save(T o) {
		// TODO Auto-generated method stub
		return this.getCurrentSession().save(o);
	}

	@Override
	public void update(T o) {
		// TODO Auto-generated method stub
		this.getCurrentSession().update(o);
	}


	
	@SuppressWarnings("unchecked")
	public List<T> find(String hql, Object[] param) {
		// TODO Auto-generated method stub
		Query<T> query= this.getCurrentSession().createQuery(hql);
		if(param!=null && param.length>0){
			for(int i=0;i<param.length;i++){
				query.setParameter(i, param[i]);
			}
		}
		return query.getResultList();
	}

}
    public class UserDAOImpl extends BaseDaoImpl<Users> implements UserDAO {

	// 根据用户名获取用户对象
	@Override
	public List getUserByLoginName(String loginName) {
		//hql查询的是实体entity 而不是数据库的表
		String hql = "from Users u where u.loginName = ?";
		Object[] param = new Object[] { loginName };
		return super.find(hql, param);
	}

	// 添加新用户
	@Override
	public void addUsers(Users u) {
		super.save(u);
	}

	// 更新用户信息
	@Override
	public void modifyUsers(Users u) {
		super.update(u);
	}

}

.
Service层开发
(7) 在项目s2sh中创建包com.restaurant.service,在包中创建接口UsersService,在UsersService接口中声明方法login,登录验证 。
(8) 创建UsersService接口的实现类UsersServiceImpl,存放在com.restaurant.service.impl包中,实现login方法。

  	public class UserServiceImpl implements UserService{

	UserDAO userDAO;
	
	
	public UserDAO getUserDAO() {
		return userDAO;
	}

	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}

	@Override
	public List getUserByLoginName(String loginName) {
		// TODO Auto-generated method stub
		return userDAO.getUserByLoginName(loginName);
	}

	@Override
	public void addUsers(Users u) {
		// TODO Auto-generated method stub
		this.userDAO.addUsers(u);
	}

	@Override
	public void modifyUsers(Users u) {
		// TODO Auto-generated method stub
		this.userDAO.modifyUsers(u);
	}

}

Action开发
在项目src目录下创建包com.restaurant.action,用于存放Action,在包中创建类UsersAction.java。

   public class UserAction extends ActionSupport implements RequestAware,ServletResponseAware,SessionAware{

	private Users u;
	
	
	
	public Users getU() {
		return u;
	}

	public void setU(Users u) {
		this.u = u;
	}

	private String repassword;

	public String getRepassword() {
		return repassword;
	}

	public void setRepassword(String repassword) {
		this.repassword = repassword;
	}

	UserService userService;

	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	public String doLogin () throws Exception {
		List  list=null;
		list=userService.getUserByLoginName(u.getLoginName());
		if(list.size()>0){
			Users users=(Users) list.get(0);
			System.out.println("=========================="+users.toString()+users.getStatus());
			if(u.getStatus() == 0){
				this.addFieldError("loginName", "该用户已被禁用,请联系管理员!");
				return "login";
			}
			if(u.getLoginPwd().equals(users.getLoginPwd())){
				session.put("user", users);
			}else {
				this.addFieldError("loginName", "密码不正确!");
				return "login";
			}
		}else {
			this.addFieldError("loginPwd", "用户名不存在!");
			return "login";
		}
		return "show";
	}
	
	public String modifyUsers() throws Exception {
		userService.modifyUsers(u);
		session.remove("user");
		session.put("user", u);
		return "show";
	}
	
	public String register() throws Exception {
		userService.addUsers(u);
		return "show";
	}
	
	public String logOut() throws Exception {
		session.remove("user");
		return "show";
	}
	
	public void validateLoginName() throws Exception {
		servletResponse.setContentType("text/html;charset=utf-8");
		PrintWriter out = servletResponse.getWriter();
		List list = userService.getUserByLoginName(u.getLoginName());
		String str = "";
		if (list.size() > 0)
			str = "{\"success\":\"true\"}";
		else
			str = "{\"success\":\"false\"}";
		out.println(str);
	}
	
	Map<String, Object> session;
	HttpServletResponse servletResponse;
	Map<String, Object> request;
	@Override
	public void setSession(Map<String, Object> arg0) {
		// TODO Auto-generated method stub
		this.session=arg0;
	}

	@Override
	public void setServletResponse(HttpServletResponse arg0) {
		// TODO Auto-generated method stub
		this.servletResponse=arg0;
	}

	@Override
	public void setRequest(Map<String, Object> arg0) {
		// TODO Auto-generated method stub
		this.request=arg0;
	}
	
}

使用strut2框架的自动验证配置xml(action名-方法名-validation.xml)

   UserAction-modifyUsers-validation.xml
    <!DOCTYPE validators PUBLIC
  	"-//Apache Struts//XWork Validator 1.0.3//EN"
  	"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>	
 	<!-- field标签里面的name表示表单里面的字段名 -->
	<field name="u.loginName">
		<field-validator type="requiredstring">
			<param name="trim">true</param>
			<message>*用户名不能为空</message>
		</field-validator>
		<field-validator type="stringlength">
			<param name="maxLength">10</param>
			<param name="minLength">4</param>
			<message>*用户名长度必须在${minLength}和${maxLength}之间</message>
		</field-validator>
	</field>

	<field name="u.loginPwd">
		<field-validator type="requiredstring">
			<param name="trim">true</param>
			<message>*密码不能为空</message>
		</field-validator>
		<field-validator type="stringlength">
			<param name="minLength">6</param>
			<message>*密码长度必须大于等于${minLength}</message>
		</field-validator>
	</field>	

	<field name="u.trueName">
		<field-validator type="requiredstring">
			<param name="trim">true</param>
			<message>*真实姓名不能为空</message>
		</field-validator>
		<field-validator type="stringlength">
			<param name="maxLength">4</param>
			<param name="minLength">2</param>
			<message>*真实姓名长度在${minLength}到${maxLength}之间</message>
		</field-validator>
	</field>

	<field name="u.address">
		<field-validator type="requiredstring">
			<param name="trim">true</param>
			<message>*通信地址不能为空</message>
		</field-validator>
		<field-validator type="stringlength">
			<param name="maxLength">30</param>
			<message>*通信地址长度不能超过${maxLength}</message>
		</field-validator>
	</field>

	<field name="u.email">
		<field-validator type="requiredstring">
			<param name="trim">true</param>
			<message>*电子邮箱不能为空</message>
		</field-validator>
		<field-validator type="email">
			<message>*电子邮箱格式不符合要求</message>
		</field-validator>
	</field>
	<field name="u.phone">
		<field-validator type="requiredstring">
			<param name="trim">true</param>
			<message>*手机号码不能为空</message>
		</field-validator>
		<field-validator type="regex">
			<param name="regexExpression"><![CDATA[^1[358]\d{9}$]]></param>
			<message>*手机号格式不正确</message>
		</field-validator>
	</field>
</validators>

Spring整合Struts 2
Spring整合Struts 2的目的在于使用Spring IOC容器来管理Struts 2的Action,整合的步骤如下所示:

 (1) 在web.xml配置文件中指定以Listerner方式启动Spring,并配置Struts 2的StrutsPrepareAndExecuteFilter,并配置过滤器。
   <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	id="WebApp_ID" version="3.1">
	<display-name>restaurantTest</display-name>
	<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>
	<!-- 指定以Listerner方式启动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>
	<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>
</web-app>
(2) 在Spring配置文件(applicationContext.xml) 中配置UsersAction类
为了保证对每个用户的请求都会创建一个新的Bean实例,在配置UsersAction的实例时,需要将<bean>元素的scope属性设置为“prototype”(原型模式)。 
<!-- 定义UserDAOImpl类 -->
	<bean id="userDAO" class="com.restaurantTest.dao.impl.UserDAOImpl">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
	<!-- 定义UserServiceImpl类,并为其userDAO属性注入值 -->
	<bean id="userService" class="com.restaurantTest.service.impl.UserServiceImpl">
		<property name="userDAO" ref="userDAO" />
	</bean>
	<!-- 定义UserAction,并为其中属性userService注入值 -->
	<bean name="userAction" class="com.restaurantTest.action.UserAction"
		scope="prototype">
		<property name="userService" ref="userService" />
	</bean>

	<!-- 将BaseDao实现类声明成一个bean并将sessionFactory注入 -->
	<bean id="baseDao" class="com.restaurantTest.dao.impl.BaseDaoImpl">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
(3) 在项目src目录下创建Struts 2的配置文件struts.xml
Spring整合Struts 2后,<action>元素中class属性不再使用UsersAction的全类名,而是引用Spring配置文件中UsersAction类的Bean实例名usersAction。  
    <!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">

<struts>
	<constant name="struts.i18n.encoding" value="utf-8"></constant>
	<!-- 定义一个名称为digital的包,继承struts 2的默认包,指定命名空间为"/" -->
	<package name="restaurantTest" namespace="/" extends="struts-default">
	<!-- 为类中的方法配置映射 -->
		<!-- 配置拦截器AuthorityInterceptor -->
	    <interceptors>
	    	<interceptor name="loginCheck" class="com.restaurant.interceptor.AuthorityInterceptor" />
	    </interceptors> 
	    <!-- 设置全局的返回值,返回首页          -->
	    <global-results>             
	    	<result name="login" type="redirectAction">toShowMeal</result>  
	    	<!-- result即action中该方法的返回值对应的结果       --> 
	    </global-results>     
	    
		<action name="doLogin" class="userAction" method="doLogin">
			<result name="show" type="redirectAction">toShowMeal</result>
			<result name="login" type="dispatcher">login.jsp</result>
		</action>
		
		<action name="register" class="userAction" method="register">			
			<result name="show" type="redirectAction">toShowMeal</result>
			<result name="input">reg.jsp</result>
		</action>
		<action name="validateLoginName" class="userAction" method="validateLoginName" />
		<action name="logOut" class="userAction" method="logOut">			
			<result name="show" type="redirectAction">toShowMeal</result>	
		</action>
		<action name="modifyUsers" class="userAction" method="modifyUsers">			
			<result name="show" type="redirectAction">toShowMeal</result>
			<result name="input">modifyMyInfo.jsp</result>	
		</action>
	</package>
</struts>