整合struts2+spring+hibernate



一、准备struts2+spring+hibernate所需要的jar包:

       新建web项目并将jar包引入到工程项目中。
整合struts2+spring+hibernate

二、搭建struts2环境


       a.在web项目的web.xml中加入struts2的过滤器,以过滤用户的所有请求,该过滤器将请求交给对应的Action处理 。
   
    <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>

       b.在项目中添加Action控制器并在项目中添加struts.xml文件对Action控制器进行配置。
       
Action:
package com.zhouxiang.action;

import com.opensymphony.xwork2.ActionSupport;
import com.zhouxiang.service.LoginService;

public class LoginAction extends ActionSupport {
	private String username;
	private String password;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String Login() {

		return "Login";
	}

	public String LoginTest() {
		if (username!=null&&password!=null)) {
			return "Success";
		} else {
			return "faliure";

		}

	}
}
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>
        
	<constant name="struts.devMode" value="true" />

	<package name="default" namespace="/" extends="struts-default">

		<!-- <default-action-ref name="index" /> -->
		<action name="Login" class="LoginAction" method="Login">
			<result name="Login">
				/Login.jsp
			</result>
		</action>
		<action name="LoginAction" class="LoginAction" method="LoginTest">
			<result name="Success">
				/LoginSuccess.jsp
			</result>
			<result name="faliure">
				/LoginSuccess.jsp
			</result>
		</action>
	</package>

	<!-- Add packages here -->

</struts>


三、搭建spring环境并整合struts2

      a.在web.xml中添加配置监听器,即把Spring 容器集成到 Web 应用里面。

<listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

      b.添加spring配置文件applicationContext.xml,Spring容器启动的时候会去读取配置信息。
      c.修改struts2配置即将Action控制器交由spring容器管理。

<constant name="struts.objectFactory" value="spring" />

四、搭建hibernate环境并与spring及struts2整合


      a.向applicationContext.xml中加入数据源配置信息——datasource bean

         <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver">
		</property>
		<property name="url" value="jdbc:mysql://localhost:3306/TestProject1"></property>
		<property name="username" value="root"></property>
		<property name="password" value="123456"></property>
         </bean>

      b.向applicationContext.xml中加入hibernate配置信息——sessionfactory bean及相应的实体映射文件配置信息

       <bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource">
		</property>

		<property name="mappingResources">
			<list>
				<value>com/zhouxiang/bean/User.hbm.xml</value>
			</list>
		</property>
		<property name="hibernateProperties">
			<value>
				hibernate.dialect=org.hibernate.dialect.MySQLDialect
				hibernate.hbm2ddl.auto=update
				hibernate.show_sql=true
				hibernate.format_sql=false
			</value>
		</property>

	</bean>


      c.将配置bean信息到applicationContext.xml中,即将项目中的bean交给spring容器管理。

        <bean id="userdao" class="com.zhouxiang.DaoImp.UserDaoImp" parent="basedaoimp">

	        <property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	<bean id="loginService" class="com.zhouxiang.service.LoginService">

		<property name="userdao" ref="userdao"></property>
	</bean>
	<bean id="LoginAction" class="com.zhouxiang.action.LoginAction">
		<property name="loginservice" ref="loginService"></property>
	</bean>

      将hibernate整合到spring中,不需要添加任何新东西,只需要导入相应的jar包,并在applicationContext.xml中加入数据源及hibernate的一些配置等配置信息即可。

五、登录demo


Login.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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="LoginAction">
用户名:<input type="text" name="username"><br>
密    码:<input type="password" name="password"><br>
<input type="submit" value="登录">
</form>
</body>
</html>

LoginAction:

package com.zhouxiang.action;

import com.opensymphony.xwork2.ActionSupport;
import com.zhouxiang.service.LoginService;

public class LoginAction extends ActionSupport {
	private String username;
	private String password;
	private LoginService loginservice;

	public LoginService getLoginservice() {
		return loginservice;
	}

	public void setLoginservice(LoginService loginservice) {
		this.loginservice = loginservice;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String Login() {
		System.out.println("hello");

		return "Login";
	}

	public String LoginTest() {
		if (loginservice.UserInfoValidate(username, password)) {
			return "Success";
		} else {
			return "faliure";

		}

	}
}

LognService

package com.zhouxiang.service;

import com.zhouxiang.DaoImp.UserDaoImp;

public class LoginService {
	private UserDaoImp userdao;
	public UserDaoImp getUserdao() {
		return userdao;
	}
	public void setUserdao(UserDaoImp userdao) {
		this.userdao = userdao;
	}
	public Boolean UserInfoValidate(String username, String password)
	{
	 if (userdao.Query(username)!=null)
		return true;
	 else
		return false;
	}

}

BaseDao接口:

package com.zhouxiang.BaseDao;

public interface BaseDao <T>{
	public Boolean Add(T t);
	public Boolean Delete(String id);
	public T Query(String id);
	public Boolean Modify(T t);

}

BaseDaoImp:
package com.zhouxiang.BaseDaoImp;

import java.lang.reflect.ParameterizedType;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.zhouxiang.BaseDao.BaseDao;

public abstract class BaseDaoImp<T> implements BaseDao<T> {
   
	private Class<T> clazz;
	private SessionFactory sessionFactory;
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public BaseDaoImp()
	{
		
		// 使用反射技术得到T的真实类型
				ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass(); // 获取当前new的对象的 泛型的父类 类型
				this.clazz = (Class<T>) pt.getActualTypeArguments()[0]; // 获取第一个类型参数的真实类型
	}
	protected Session getSession()
	{
		return sessionFactory.openSession();
	}
	@Override
	public Boolean Add(T t) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Boolean Delete(String id) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public T Query(String id) {
		// TODO Auto-generated method stub
		if(id==null)
				{
			return null;
				}
		else{
			System.out.println("sdfsd");
			return (T) getSession().get(clazz, id);
		   }
	}
	

	@Override
	public Boolean Modify(T t) {
		// TODO Auto-generated method stub
		return null;
	}

}

UserDao接口:

package com.zhouxiang.Dao;

import com.zhouxiang.BaseDao.BaseDao;
import com.zhouxiang.bean.User;

public interface UserDao extends BaseDao<User> {

}

UserDaoImp :

package com.zhouxiang.DaoImp;

import com.zhouxiang.BaseDaoImp.BaseDaoImp;
import com.zhouxiang.Dao.UserDao;
import com.zhouxiang.bean.User;

public class UserDaoImp extends BaseDaoImp<User> implements UserDao {

}

项目配置文件web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	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_2_5.xsd">
  <display-name></display-name>	
  <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>
 <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- Application Listener for Mailreader database 
    <listener>
        <listener-class>
            mailreader2.ApplicationListener
        </listener-class>
    </listener>
-->
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

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>
        
	<constant name="struts.objectFactory" value="spring" />


	<package name="default" namespace="/" extends="struts-default">

		<!-- <default-action-ref name="index" /> -->
		<action name="Login" class="LoginAction" method="Login">
			<result name="Login">
				/Login.jsp
			</result>
		</action>
		<action name="LoginAction" class="LoginAction" method="LoginTest">
			<result name="Success">
				/LoginSuccess.jsp
			</result>
			<result name="faliure">
				/LoginSuccess.jsp
			</result>
		</action>
	</package>


	<!-- Add packages here -->

</struts>

applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>

<!-- - Application context definition for JPetStore's business layer. - Contains 
	bean references to the transaction manager and to the DAOs in - dataAccessContext-local/jta.xml 
	(see web.xml's "contextConfigLocation"). -->
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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-2.5.xsd
			http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
			http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">


	<!-- ========================= GENERAL DEFINITIONS ========================= -->

	<!-- Configurer that replaces ${...} placeholders with values from properties 
		files -->
	<!-- (in this case, mail and JDBC related properties) -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver">
		</property>
		<property name="url" value="jdbc:mysql://localhost:3306/TestProject1"></property>
		<property name="username" value="root"></property>
		<property name="password" value="123456"></property>
	</bean>
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource">
		</property>

		<property name="mappingResources">
			<list>
				<value>com/zhouxiang/bean/User.hbm.xml</value>
			</list>
		</property>
		<property name="hibernateProperties">
			<value>
				hibernate.dialect=org.hibernate.dialect.MySQLDialect
				hibernate.hbm2ddl.auto=update
				hibernate.show_sql=true
				hibernate.format_sql=false
			</value>
		</property>

	</bean>
	<bean id="basedaoimp" class="com.zhouxiang.BaseDaoImp.BaseDaoImp"
		abstract="true">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	<bean id="userdao" class="com.zhouxiang.DaoImp.UserDaoImp" parent="basedaoimp">

		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	<bean id="loginService" class="com.zhouxiang.service.LoginService">

		<property name="userdao" ref="userdao"></property>
	</bean>
	<bean id="LoginAction" class="com.zhouxiang.action.LoginAction">
		<property name="loginservice" ref="loginService"></property>
	</bean>
</beans>

六、总结

      SSH的环境搭建没有什么难度,需要的只是一些jar包和一些配置文件。struts+spring+hibernate整合的过程中需要注意的是引入的一些jar包及为什么使用这些jar包,这些jar包的作用是什么。当然必不可少的还有一些配置文件,如web项目初始化需要做的,如何将spring容器加入到项目中,一集如何将struts跟hibernate、及项目中用到的实体bean、业务逻辑bean交给spring容器管理。整个环境搭建的过程最重要的是去理解三大框架是如何独立工作的,又是如何衔接工作的。



整合struts2+spring+hibernate

上一篇:Struts1.X与Spring集成——第二种方案


下一篇:Python写WEB日志分析程序的一些思路