现在的位置: 首页 > 综合 > 正文

SSH框架整合

2013年04月30日 ⁄ 综合 ⁄ 共 14608字 ⁄ 字号 评论关闭

struts2.3.4+spring3.2+hibernate4.1.1

第一步:导入框架所需要的包

 网盘资源地址:

http://pan.baidu.com/share/link?shareid=119830&uk=909074031

第二步:修改web.xml文件

<?xml version="1.0"encoding="UTF-8"?>
<web-app 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_3_0.xsd"
    version="3.0">
    <!-- Welcome File List -->
    <welcome-file-list 配置欢迎界面>
        <welcome-file>test.jsp</welcome-file>
    </welcome-file-list>
    <!-- WebApp Root -->
    <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>SSH</param-value>
    </context-param>
    <!-- Spring Encoding Filter -->
    <filter>
        <filter-name>encodingFilter</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>
    </filter>
    <!-- Spring Encoding Filter Mapping-->
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- Struts2 Filter -->
    <filter>
        <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <!-- Struts2 Filter Mapping -->
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- Log4j ConfigurationFile Location Log4j 日志系统本地信息的配置-->
    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>classpath:log4j.properties</param-value>
    </context-param>
    <!-- Spring Log4j Listener -->
    <listener>
        <listener-class>
           org.springframework.web.util.Log4jConfigListener
        </listener-class>
    </listener>
    <!-- Spring ConfigurationFile Location spring的xml配置文件-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <!-- Spring Context Listener -->
    <listener>
        <listener-class>
           org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
    <!-- Spring Web Request Listener -->
    <listener>
        <listener-class>
           org.springframework.web.context.request.RequestContextListener
        </listener-class>
    </listener>
    <!-- Spring 防止内存溢出Spring Introspector Cleanup Listener -->
    <listener>
        <listener-class>
           org.springframework.web.util.IntrospectorCleanupListener
        </listener-class>
    </listener>
</web-app>

第三步:添加LOG4J的配置文件

# Set The RootLogger
log4j.rootLogger=info,console,html,txt
# Direct Log Messages ToConsole
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Target=System.out
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %p %c:%L - %m%n
#html
log4j.appender.html=org.apache.log4j.RollingFileAppender
log4j.appender.html.File=c:/log.html
log4j.appender.html.MaxFileSize=900KB
log4j.appender.html.MaxBackupIndex=1
log4j.appender.html.layout=org.apache.log4j.HTMLLayout
log4j.appender.html.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c] [%p] - %m%n
#\u6587\u672c\u6587\u4ef6\u8f93\u51fa\u6e90
log4j.appender.txt=org.apache.log4j.RollingFileAppender
log4j.appender.txt.File=c:/log.txt
log4j.appender.txt.MaxFileSize=500KB
log4j.appender.txt.MaxBackupIndex=1
log4j.appender.txt.layout=org.apache.log4j.PatternLayout
log4j.appender.txt.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c] [%p] - %m%n
# Log Hibernate
log4j.logger.org.hibernate=info
# Log Just The SQL
log4j.logger.org.hibernate.SQL=info
# Log Schema Export Update
log4j.logger.org.hibernate.tool.hbm2ddl=info

第四步:创建hibernate.cfg.xml

<!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>
        <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>       
        <property name="hibernate.hbm2ddl.auto">update</property>
        <property name="hibernate.format_sql">true</property>
        <property name="hibernate.show_sql">true</property>
        <mapping resource="entity/Person.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

第五步:struts.xml

<?xml version="1.0"encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD StrutsConfiguration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
    <constant name="struts.devMode" value="false" />
    <constant name="struts.i18n.encoding" value="UTF-8" />
    <package name="default"  extends="struts-default">
        <action name="person_*"method="{1}" class="action.PersonAction">
            <result name="input">/index.jsp</result>
            <result name="ok">/index.jsp</result>
            <result name="ajax-json">/ajax.jsp</result>
        </action>
    </package>
</struts>

第六步:applicationContext.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"    
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.1.xsd


http://www.springframework.org/schema/aop


http://www.springframework.org/schema/aop/spring-aop-3.1.xsd


http://www.springframework.org/schema/tx


http://www.springframework.org/schema/tx/spring-tx-3.1.xsd


http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:component-scan base-package="action,dao,biz,util"/>
    <!-- DataSource -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
        destroy-method="close">    
        <property name="driverClass"value="oracle.jdbc.driver.OracleDriver"/>
        <property name="jdbcUrl" value="jdbc:oracle:thin:@192.168.3.186:1521:orcl"/>
        <property name="user" value="bam1"/>
        <property name="password" value="bam1"/>
    </bean>
    <!—SessionFactory的注入-->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
        p:dataSource-ref="dataSource" 
       p:configLocation="classpath:hibernate.cfg.xml"/>
<!-- SessionFactory 另一种配置hibernate属性的信息,通过这种方式配置,就不需要hibernate.cfg.xml文件
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
        p:dataSource-ref="dataSource" >
        <propertyname="hibernateProperties">
        <props>
             <propkey="hibernate.show_sql">true</prop>
             <propkey="hibernate.format_sql">true</prop>
             <propkey="hibernate.hbm2ddl.auto">update</prop>
             <propkey="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
        </props>
        </property>
        <property name="mappingResouce">
        <list>
              //各种实体映射文件
             <value>entity/Person.hbm.xml</value>
             <value>entity/Person.hbm.xml</value>
             <value>entity/Person.hbm.xml</value>
             <value>entity/Person.hbm.xml</value>
        </list>
        </property>
    </bean>
    -->
</beans>

第七步:工具辅助类HibernateUtil

package util;
importjava.io.Serializable;
import java.util.ArrayList;
importjava.util.List;
importjavax.annotation.Resource;
importorg.hibernate.Criteria;
importorg.hibernate.Query;
importorg.hibernate.Session;
importorg.hibernate.SessionFactory;
importorg.hibernate.Transaction;
importorg.hibernate.criterion.DetachedCriteria;
import org.springframework.stereotype.Component;
/**
 * @author Administrator 工具类适用于WEB版,通过SPRING容器注入SessionFactory
 */
@Component
public classHibernateUtil {
         @Resource(name = "sessionFactory")
         private SessionFactory factory;  //这里名称指向applicationContext.xml中注入的bean名
         /**
          * @return返回会话工厂
          */
         public SessionFactory getFactory() {
                   return factory;
         }
         /**
          * @return返回会话
          */
         public Session getSession() {
                   return factory.openSession();
         }
         /**
          * @param obj
          * @return返回是否添加成功
          */
         public boolean add(Object obj) {
                   Session s = null;
                   Transaction t = null;
                   boolean result = false;
                   try {
                            s = getSession();
                            t =s.beginTransaction();
                            s.save(obj);
                            t.commit();
                            result = true;
                   } catch (Exception e) {
                            if (t != null)
                                     t.rollback();
                            e.printStackTrace();
                   } finally {
                            if (s != null)
                                     s.close();
                   }
                   return result;
         }
         /**
          * @param obj
          * @return返回是否修改成功
          */
         public boolean update(Object obj) {
                   Session s = null;
                   Transaction t = null;
                   boolean result = false;
                   try {
                            s = getSession();
                            t =s.beginTransaction();
                            s.update(obj);
                            t.commit();
                            result = true;
                   } catch (Exception e) {
                            if (t != null)
                                     t.rollback();
                            e.printStackTrace();
                   } finally {
                            if (s != null)
                                     s.close();
                   }
                   return result;
         }
         /**
          * @param obj
          * @return返回是否删除成功
          */
         public boolean delete(Object obj) {
                   Session s = null;
                   Transaction t = null;
                   boolean result = false;
                   try {
                            s = getSession();
                            t =s.beginTransaction();
                            s.delete(obj);
                            t.commit();
                            result = true;
                   } catch (Exception e) {
                            if (t != null)
                                     t.rollback();
                            e.printStackTrace();
                   } finally {
                            if (s != null)
                                     s.close();
                   }
                   return result;
         }
         /**
          * @param cla
          * @param id
          * @return根据主键ID查询一条数据
          */
         @SuppressWarnings("unchecked")
         public <T> T get(Class<T>cla, Serializable id) {
                   Session s = null;
                   T obj = null;
                   try {
                            s = getSession();
                            obj = (T) s.get(cla,id);
                   } catch (Exception e) {
                            e.printStackTrace();
                   } finally {
                            if (s != null)
                                     s.close();
                   }
                   return obj;
         }
         /**
          * @param hql语句
          * @param pras参数数组
          * @param isCache是否要缓存数据
          * @return返回多条数据
          */
         public <T> List<T>query(String hql, boolean isCache, Object... pras) {
                   List<T> list = new ArrayList<T>();
                   Session s = null;
                   try {
                            s = getSession();
                            Query q =s.createQuery(hql);
                            // 设置允许二级缓存
                            q.setCacheable(isCache);
                            if (pras != null) {
                                     for (int i= 0; i < pras.length; i++) {
                                               q.setString(i,pras[i].toString());
                                     }
                            }
                            list = q.list();
                   } catch (Exception e) {
                            e.printStackTrace();
                   } finally {
                            if (s != null)
                                     s.close();
                   }
                   return list;
         }
         /**
          * @param <T>
          * @param hql语句
          * @param pras参数
          * @param page当前第几页
          * @param size一页显示数据个数
          * @return分页获取数据
          */
         public <T> List<T>queryByPage(String hql, int page, int size,
                            Object... pras) {
                   List<T> list = newArrayList<T>();
                   Session s = null;
                   try {
                            s = getSession();
                            Query q =s.createQuery(hql);
                            if (pras != null) {
                                     for (int i= 0; i < pras.length; i++) {
                                               q.setString(i,pras[i].toString());
                                     }
                            }
                            // 设置开始记录数
                            q.setFirstResult((page- 1) * size);
                            // 设置每页获取的数据数量
                            q.setMaxResults(size);
                            list = q.list();
                   } catch (Exception e) {
                            e.printStackTrace();
                   } finally {
                            if (s != null)
                                     s.close();
                   }
                   return list;
         }
         /**
          * @param hql语句
          * @param pras参数
          * @return
          * @return返回单条查询数据
          */
         public <T> T queryUnique(Stringhql, Object... pras) {
                   T obj = null;
                   Session s = null;
                   try {
                            s = getSession();
                            Query q =s.createQuery(hql);
                            if (pras != null) {
                                     for (int i= 0; i < pras.length; i++) {
                                               q.setString(i,pras[i].toString());
                                     }
                            }
                            obj = (T)q.uniqueResult();
                   } catch (Exception e) {
                            e.printStackTrace();
                   } finally {
                            if (s != null)
                                     s.close();
                   }
                   return obj;
         }
         public <T> List<T>dcQuery(DetachedCriteria dc) {
                   Session s = getSession();
                   Criteria c =dc.getExecutableCriteria(s);
                   List list = c.list();
                   s.close();
                   return list;
         }
}

第八步:数据层操作的接口

package dao;
importjava.util.List;
importorg.hibernate.criterion.DetachedCriteria;
 
/**
 * @author Administrator 通过的数据操作接口
 */
public interfaceBaseDao {
         /**
          * @param <T>
          * @param t添加
          */
         public <T> void save(T t);
         /**
          * @param <T>
          * @param t删除
          */
         public <T> void delete(T t);
         /**
          * @param <T>
          * @param entityClass
          * @param id根据主键ID删除
          */
         public <T> void delete(Class<T>entityClass, Integer id);
         /**
          * @param <T>
          * @param t更新数据
          */
         public <T> void update(T t);
         /**
          * @param <T>
          * @param entityClass
          * @param id
          * @return根据ID查询单条数据,适用于JDBC的操作,不适用于hibernate
          */
         public <T> T get(Class<T>entityClass, Integer id);
         /**
          * @param <T>
          * @param entityClass
          * @param pras
          * @return根据多个条件查询,但返回数据必须是单条数据
          */
         public <T> T get(Class<T>entityClass, String hql, Object... pras);
         /**
          * @param <T>
          * @param hql
          * @param entityClass
          * @param param
          * @return根据条件或无条件查询多条数据
          */
         public <T> List<T>findAll(String hql, Class<T> entityClass,
                            Object... param);
         /**
          * @param <T>
          * @param hql
          * @param entityClass
          * @param page页数
          * @param size每页显示的数据记录数
          * @param param
          * @return根据条件或无条件,分页获取数据
          */
         public <T> List<T>findByPage(String hql, Class<T> entityClass, int page,
                            int size, Object...param);
         /**
          * @param hql
          * @param param
          * @return获取通过聚合函数取到的数据,如获取总的记录数
          */
         public int findCount(String hql,Object... param);
         public ObjectfindByOne(DetachedCriteria dc);
}

第九步:数据层操作类的实现

package dao;
importjava.util.List;
importjavax.annotation.Resource;
importorg.hibernate.criterion.DetachedCriteria;
import org.springframework.stereotype.Repository;
importutil.HibernateUtil;
/**
 * @author Administrator 通过表数据操作类
 */
@Repository
public classBaseDaoImpl implements BaseDao {
         @Resource
         private HibernateUtil util;
 
         public <T> void save(T t) {
                   util.add(t);
         }
         public <T> void update(T t) {
                   util.update(t);
         }
         public <T> void delete(T t) {
                   util.delete(t);
         }
         public <T> voiddelete(Class<T> entityClass, Integer id) {
                   // JDBC使用
         }
         public <T> List<T>findAll(String hql, Class<T> entityClass,
                            Object... param) {
                   return util.query(hql, false,param);
         }
         public <T> List<T>findByPage(String hql, Class<T> entityClass, int page,
                            int size, Object...param) {
                   // TODO Auto-generated methodstub
                   return util.queryByPage(hql,page, size, param);
         }
         public <T> T get(Class<T>entityClass, Integer id) {
                   // TODO Auto-generated methodstub
                   return util.get(entityClass,id);
         }
         public <T> T get(Class<T>entityClass, String hql, Object... pras) {
                   // TODO Auto-generated methodstub
                   return util.queryUnique(hql,pras);
         }
         public int findCount(String hql,Object... param) {
                   // TODO Auto-generated methodstub
                   Object[] obj =util.queryUnique(hql, param);
                   returnInteger.parseInt(obj[0].toString());
         }
         public ObjectfindByOne(DetachedCriteria dc) {
                   // TODO Auto-generated methodstub
                   return util.dcQuery(dc).size();
         }
}

第十步:编写实体类映射元文件

<hibernate-mapping package="entity">
    <class name="Person" table="t_person">
        <id name="personId">
            <generator class="native"/>
        </id>
        <property name="personName"/>
    </class>
</hibernate-mapping>

第十一步:编写业务逻辑层接口和实现类

package biz;
import java.util.List;
import entity.Person;
public interface PersonBiz {
public void add(Person person);
public void update(Person person);
public void delete(int id);
public Person queryByUnique(int id);
public List<Person> queryByAll();
public List<Person> queryByPage(intpage, int size);
public int getCount();
}
   实现类
 packagebiz;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import util.LogUtil;
import dao.BaseDao;
import entity.Person;
@Service  //注解
public class PersonBizImpl implementsPersonBiz {
       @Resource   //注解
       privateBaseDao dao;
       publicvoid add(Person person) {
              //TODO Auto-generated method stub
              dao.save(person);
              LogUtil.getLog(PersonBizImpl.class).info(
                            "执行了添加用户的操作:用户名=" +person.getPersonName());
       }
       publicvoid delete(int id) {
              dao.delete(newPerson(id));
       }
       publicint getCount() {
              //TODO Auto-generated method stub
              //使用多条件查询时
              //DetachedCriteria dc = DetachedCriteria.forClass(Person.class);
              //for (int i = 0; i < fieds.length; i++) {
              //dc.add(Restrictions.eq(fieds[i], value[i]));
              //}
              returndao.findCount("select count(*) from Person");
       }
       publicList<Person> queryByAll() {
              //TODO Auto-generated method stub
              returndao.findAll("from Person", Person.class);
       }
       publicList<Person> queryByPage(int page, int size) {
              //TODO Auto-generated method stub
              returndao.findByPage("from Person", Person.class, page, size);
       }
       publicPerson queryByUnique(int id) {
              //TODO Auto-generated method stub
              returndao.get(Person.class, id);
       }
       publicvoid update(Person person) {
              //TODO Auto-generated method stub
              dao.update(person);
       }
}

第十二步:编写Action类

package action;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import biz.PersonBiz;
import com.google.gson.Gson;
import entity.Person;
@Controller
public class PersonAction {
       privateString message;
       privatePerson person;
       publicString getMessage() {
              returnmessage;
       }
       publicvoid setMessage(String message) {
              this.message= message;
       }
       publicPerson getPerson() {
              returnperson;
       }
       publicvoid setPerson(Person person) {
              this.person= person;
       }
       @Resource
       privatePersonBiz biz;
       publicString add() {
              biz.add(person);
              setMessage("添加成功!");
              return"ok";
       }
       publicString query() {
              Gsonjson = new Gson();
              List<Person>list = biz.queryByAll();
              Stringstr = json.toJson(list);
              setMessage(str);
              return"ajax-json";
       }
}

抱歉!评论已关闭.