Struts+Spring+Hibernate/SSH整合开发详细二

2008年06月13日 星期五 0:46

SSH相关配置文件以及UserDao(系MyEclipse自动生成) 整合示例请您阅读Struts+Spring+Hibernate/SSH整合开发详细一

/****************************************************struts-config.xml****************************************************/

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">

<!-- Struts 配置文件中的元素配置时是有一定顺序的 -->
<struts-config>
<data-sources />
<form-beans>
   <form-bean name="userForm"
    type="com.wuwei.struts.form.UserForm">
   </form-bean>
</form-beans>

<global-exceptions />
<global-forwards />
<action-mappings>
   <action path="/validateUser"
    type="com.wuwei.struts.action.ValidateUserAction" name="userForm">
    <forward name="success" path="/success.jsp"></forward>
    <forward name="fail" path="/fail.jsp"></forward>
   </action>

</action-mappings>

<!-- 加上controller就不用再配置action的type属性了/或者说type属性不用改为
   type="org.springframework.web.struts.DelegatingActionProxy" -->
<controller
   processorClass="org.springframework.web.struts.DelegatingRequestProcessor">
</controller>

<message-resources
   parameter="com.wuwei.struts.ApplicationResources" />

<plug-in
   className="org.springframework.web.struts.ContextLoaderPlugIn">
   <set-property property="contextConfigLocation"
    value="/WEB-INF/classes/applicationContext.xml" />
</plug-in>

<!-- 如下配置的话,就可以不在Action中配置type属性了 -->
<!--<controller>
   <set-property property="processorClass"
   value="org.springframework.web.struts.DelegatingRequestProcessor" />
   </controller>-->

<!--配置一个插件去集成spring -->
<!--<plug-in
   className="org.springframework.web.struts.ContextLoaderPlugIn">
   <set-property property="contextConfigLocation"
   value="/WEB-INF/applicationContext.xml" />
   </plug-in>-->
</struts-config>

/*********************************************….hbm.xml************************************************/

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- 
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <!-- <class name="com.wuwei.struts.bean.User" table="user" schema="dbo" catalog="test">-->
    <class name="com.wuwei.struts.bean.User" table="user" lazy="false">
        <id name="ID" type="java.lang.Integer">
            <column name="id" />
            <generator class="increment" />
        </id>
        <property name="username" type="java.lang.String">
            <column name="username" length="8" />
        </property>
        <property name="pwd" type="java.lang.String">
            <column name="pwd" length="8" />
        </property>
    </class>
</hibernate-mapping>

 

/*******************************************************applicationConfig.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

<!-- 数据源部分 -->
<bean id="dataSource"
   class="org.apache.commons.dbcp.BasicDataSource">
   <property name="driverClassName"
    value="net.sourceforge.jtds.jdbc.Driver">
   </property>
   <property name="url"
    value="jdbc:jtds:sqlserver://localhost:1433/test">
   </property>
   <property name="username" value="sa"></property>
   <property name="password" value="admin"></property>
</bean>

<!-- 将Hibernate交由Spring管理(Hibernate相关配置信息) ,创建SessionFactory-->
<bean id="sessionFactory"
   class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
   <property name="dataSource">
    <ref bean="dataSource" />
   </property>
   <property name="hibernateProperties">
    <props>
     <prop key="hibernate.dialect">
      org.hibernate.dialect.SQLServerDialect
     </prop>
     <prop key="hibernate.show_sql">true</prop>
    </props>
   </property>
   <property name="mappingResources">
    <list>
     <value>com/wuwei/struts/dao/User.hbm.xml</value>
    </list>
   </property>
</bean>

<!-- 通过HibernateDaoSupport来操作数据库,需要植入sessionFactory 
   UserDao继承自HibernateDaoSupport
-->
<bean id="userDao" class="com.wuwei.struts.dao.UserDAO">
   <property name="sessionFactory" ref="sessionFactory" />
</bean>

<!-- 
   如果想在某个Dao类中直接使用HibernateTemplate来操作数据库,则需要按如下配置 
   上述的HibernateDaoSupport其实也是利用HibernateTemplate来操作数据库的,只是做
   了一些封装。刚开始还一直在想,哪种实现方式好了,这样看来,还是看个人习惯吧。
-->
<!-- 
   <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
    <property name="sessionFactory" ref="sessionFactory" />
   </bean>
  
   <bean id="userDao" class="com.wuwei.struts.dao.UserDAO">
    <property name="hibernateTemplate" ref="hibernateTemplate" />
   </bean>
-->

<!-- Struts -->
<bean name="/validateUser"
   class="com.wuwei.struts.action.ValidateUserAction">
   <property name="userDAO" ref="userDao" />

</bean>
</beans>

 

/****************************************************UserDAO.java****************************************************/


package com.wuwei.struts.dao;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.wuwei.struts.bean.User;

/**
* Data access object (DAO) for domain model class User.

* @see com.wuwei.struts.dao.User
* @author MyEclipse Persistence Tools
*/
public class UserDAO extends HibernateDaoSupport{

private static final Log log    = LogFactory.getLog(UserDAO.class);

// property constants
public static final String USERNAME = "username";

public static final String PWD    = "pwd";

protected void initDao()
{
// do nothing
}

public void save(User transientInstance)
{
   log.debug("saving User instance");
   try
   {
    getHibernateTemplate().save(transientInstance);
    log.debug("save successful");
   }
   catch (RuntimeException re)
   {
    log.error("save failed", re);
    throw re;
   }
}

public void delete(User persistentInstance)
{
   log.debug("deleting User instance");
   try
   {
    getHibernateTemplate().delete(persistentInstance);
    log.debug("delete successful");
   }
   catch (RuntimeException re)
   {
    log.error("delete failed", re);
    throw re;
   }
}

public User findById(java.lang.Integer id)
{
   log.debug("getting User instance with id: " + id);
   try
   {
    User instance = (User) getHibernateTemplate().get("com.wuwei.struts.dao.User", id);
    return instance;
   }
   catch (RuntimeException re)
   {
    log.error("get failed", re);
    throw re;
   }
}

public List findByExample(User instance)
{
   log.debug("finding User instance by example");
   try
   {
    List results = getHibernateTemplate().findByExample(instance);
    log.debug("find by example successful, result size: " + results.size());
    return results;
   }
   catch (RuntimeException re)
   {
    log.error("find by example failed", re);
    throw re;
   }
}

public List findByProperty(String propertyName, Object value)
{
   log.debug("finding User instance with property: " + propertyName + ", value: " + value);
   try
   {
    String queryString = "from User as model where model." + propertyName + "= ?";
    return getHibernateTemplate().find(queryString, value);
   }
   catch (RuntimeException re)
   {
    log.error("find by property name failed", re);
    throw re;
   }
}

public List findByUsername(Object username)
{
   return findByProperty(USERNAME, username);
}

public List findByPwd(Object pwd)
{
   return findByProperty(PWD, pwd);
}

public List findAll()
{
   log.debug("finding all User instances");
   try
   {
    String queryString = "from User";
    return getHibernateTemplate().find(queryString);
   }
   catch (RuntimeException re)
   {
    log.error("find all failed", re);
    throw re;
   }
}

public User merge(User detachedInstance)
{
   log.debug("merging User instance");
   try
   {
    User result = (User) getHibernateTemplate().merge(detachedInstance);
    log.debug("merge successful");
    return result;
   }
   catch (RuntimeException re)
   {
    log.error("merge failed", re);
    throw re;
   }
}

public void attachDirty(User instance)
{
   log.debug("attaching dirty User instance");
   try
   {
    getHibernateTemplate().saveOrUpdate(instance);
    log.debug("attach successful");
   }
   catch (RuntimeException re)
   {
    log.error("attach failed", re);
    throw re;
   }
}

public void attachClean(User instance)
{
   log.debug("attaching clean User instance");
   try
   {
    getHibernateTemplate().lock(instance, LockMode.NONE);
    log.debug("attach successful");
   }
   catch (RuntimeException re)
   {
    log.error("attach failed", re);
    throw re;
   }
}

public static UserDAO getFromApplicationContext(ApplicationContext ctx)
{
   return (UserDAO) ctx.getBean("UserDAO");
}
}

 

/****************************************************ValidateUserAction.java****************************************************/


package com.wuwei.struts.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.wuwei.struts.bean.User;
import com.wuwei.struts.dao.UserDAO;
import com.wuwei.struts.form.UserForm;

public class ValidateUserAction extends Action{

UserDAO userDAO = null;

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

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response)
{
   UserForm userForm = (UserForm) form;
   List list = userDAO.findByUsername(userForm.getUsername());
   if (0 < list.size())
   {
    User user = (User) list.get(0);
    if (user.getPwd().equals(userForm.getPwd()))
     return mapping.findForward("success");
    else
     return mapping.findForward("fail");
   }
   else
    return mapping.findForward("fail");
   // System.out.println("I'm in a Action");
   // return null;
}
}