迷失北京

          BlogJava 聯系 聚合 管理
            60 Posts :: 0 Stories :: 13 Comments :: 0 Trackbacks

          Struts2+Hibernate+Spring環境的搭建

                最近這些天一直在學習ssh,有的人說沒有必要為了學習框架而學習框架?。∥矣X得自己就是為了學習框架而學習框架,不過也是形勢所逼呀!暫且不管別人是怎么說的了,學習這種東西只要學習了就是自己的,相信知識是不會白學習的,不要“書到用時方恨少”,哈哈...有點未雨綢繆的意思了。先學習用著再說,然后逐步提高吧還是??!

                把具體的搭建過程記錄一下:(項目運行環境:Myeclipse+Mysql+JDK1.6)

                步驟一:在Myeclipse中創建三個user liberary分別是struts2,hibernate,spring運行所必需的jar包,創建項目后引入剛才創建的三個liberary。

                步驟二:修改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">
          	
          	<!-- 配置加載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>
          	<!-- lazy initial session自動關閉,但是頁面請求未完成!-->
          	<!-- 第二種解決方案openSessionInViewInterceptor -->
          	<filter>
          		<filter-name>openSessionInView</filter-name>
          		<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
          	</filter>
          	<filter-mapping>
          		<filter-name>openSessionInView</filter-name>
          		<url-pattern>/*</url-pattern>
          	</filter-mapping>
          	
          	
          	<!-- struts2 -->
          	<filter>
          		<filter-name>struts2</filter-name>
          		<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
          	</filter>
          	<filter-mapping>
          		<filter-name>struts2</filter-name>
          		<url-pattern>/*</url-pattern>
          	</filter-mapping>
          	
          	
            <welcome-file-list>
              <welcome-file>index.jsp</welcome-file>
            </welcome-file-list>
          </web-app>
          

            

                步驟三:修改spring的配置文件,具體代碼如下:

          <?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-3.0.xsd
                     http://www.springframework.org/schema/context
                     http://www.springframework.org/schema/context/spring-context-3.0.xsd
                     http://www.springframework.org/schema/aop
                     http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
                     http://www.springframework.org/schema/tx           
                     http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
          	<context:annotation-config />
          	<!-- 根據annotation注入 -->
          	<context:component-scan base-package="com.wk" />
          	<!-- 創建dataSource -->
          	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
          		destroy-method="close">
          		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
          		<property name="url" value="jdbc:mysql://localhost:3306/spring" />
          		<property name="username" value="root" />
          		<property name="password" value="wangkang" />
          	</bean>
          	<!-- 整合hibernate -->
          	<bean id="sessionFactory"
          		class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
          		<property name="dataSource" ref="dataSource" />
          		<property name="packagesToScan">
          			<list>
          				<value>com.wk.model</value>
          			</list>
          		</property>
          		<property name="hibernateProperties">
          			<props>
          				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
          				<prop key="hibernate.show_sql">true</prop>
          			</props>
          		</property>
          	</bean>
          	<!-- spring_xml事務管理-->
          	<bean id="txManager"
          		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
          		<property name="sessionFactory" ref="sessionFactory" />
          	</bean>
          	<aop:config>
          		<aop:pointcut id="serviceBusiness" expression="execution(public * com.web..*.add(..))" />
          		<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceBusiness"
          			order="2" />
          	</aop:config>
          	<tx:advice id="txAdvice" transaction-manager="txManager">
          		<tx:attributes>
          			<tx:method name="get*" read-only="true" />
          			<tx:method name="add*" propagation="REQUIRED" />
          		</tx:attributes>
          	</tx:advice>
          	<!-- HibernateTemplate -->
          	<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
          		<property name="sessionFactory">
          			<ref bean="sessionFactory" />
          		</property>
          	</bean>
          </beans>
          

            

          spring注入的時候用的是Annotation 的方式,hibernate映射的時候也是用的Annotation的方式 。

                貼出其他的代碼,主要是配置文件寫的時候比較費勁,其他的東西還是比較好搞定的:

                1.model---Person

          package com.wk.model;
          import javax.persistence.Entity;
          import javax.persistence.GeneratedValue;
          import javax.persistence.Id;
          import org.springframework.stereotype.Component;
          @Entity
          @Component("person")
          public class Person {
          	private int id;
          	private String name;
          	private String address;
          	private String profession;
          	public Person() {
          		super();
          	}
          	@Id
          	@GeneratedValue
          	public int getId() {
          		return id;
          	}
          	public void setId(int id) {
          		this.id = id;
          	}
          	public String getName() {
          		return name;
          	}
          	public void setName(String name) {
          		this.name = name;
          	}
          	public String getAddress() {
          		return address;
          	}
          	public void setAddress(String address) {
          		this.address = address;
          	}
          	public String getProfession() {
          		return profession;
          	}
          	public void setProfession(String profession) {
          		this.profession = profession;
          	}
          }
          

            

                2.dao---PersonDAO

          package com.wk.dao;
          import com.wk.model.Person;
          public interface PersonDAO {
          	public int save(Person person);
          	public int delete(int id);
          	public int update(Person person);
          	public Person getPerson(int id);
          }
          

            

                3.impl---PersonDAOImpl

          package com.wk.dao.impl;
          import org.hibernate.HibernateException;
          import org.hibernate.Session;
          import org.springframework.stereotype.Component;
          import com.wk.dao.PersonDAO;
          import com.wk.model.Person;
          import com.wk.util.HibernateUtil;
          @Component("personDAO")
          public class PersonDAOImpl implements PersonDAO {
          	public int delete(int id) {
          		Session session = HibernateUtil.getSessionfactory().getCurrentSession();
          		Person person = new Person();
          		try {
          			session.beginTransaction();
          			person.setId(id);
          			session.delete(person);
          			session.beginTransaction().commit();
          			return 1;
          		} catch (HibernateException e) {
          			e.printStackTrace();
          		}
          		return 0;
          	}
          	public Person getPerson(int id) {
          		Session session = HibernateUtil.getSessionfactory().getCurrentSession();
          		Person person = new Person();
          		try {
          			session.beginTransaction();
          			person = (Person) session.get(Person.class, id);
          			session.beginTransaction().commit();
          			return person;
          		} catch (HibernateException e) {
          			e.printStackTrace();
          		}
          		return null;
          	}
          	public int save(Person person) {
          		Session session = HibernateUtil.getSessionfactory().getCurrentSession();
          		try {
          			session.beginTransaction();
          			session.save(person);
          			session.beginTransaction().commit();
          			return 1;
          		} catch (HibernateException e) {
          			e.printStackTrace();
          		}
          		return 0;
          	}
          	public int update(Person personVo) {
          		Session session = HibernateUtil.getSessionfactory().getCurrentSession();
          		Person person = new Person();
          		try {
          			session.beginTransaction();
          			person = (Person) session.load(Person.class, personVo.getId());
          			
          			person.setName(personVo.getName());
          			person.setAddress(personVo.getAddress());
          			person.setProfession(personVo.getProfession());
          			
          			session.update(person);
          			session.flush();//提高效率
          			session.beginTransaction().commit();
          			return 1;
          		} catch (HibernateException e) {
          			e.printStackTrace();
          		}
          		return 0;
          	}
          }
          

            

                4.strutsAction---PersonAction

          package com.wk.action;
          import javax.annotation.Resource;
          import org.springframework.stereotype.Component;
          import com.opensymphony.xwork2.ActionSupport;
          import com.wk.dao.PersonDAO;
          import com.wk.dao.impl.PersonDAOImpl;
          import com.wk.model.Person;
          @Component("personAction")
          public class PersonAction extends ActionSupport {
          	private static final long serialVersionUID = -3699819837781302739L;
          	PersonDAO personDAO = new PersonDAOImpl();
          	Person person = new Person();
          	int id = 0;
          	public String addPerson() {
          		int flag = personDAO.save(person);
          		if (flag == 1) {
          			return "success";
          		} else {
          			return "fail";
          		}
          	}
          	public String delPerson() {
          		int flag = personDAO.delete(id);
          		if (flag == 1) {
          			return "success";
          		} else {
          			return "fail";
          		}
          	}
          	public String updatePerson() {
          		int flag = personDAO.update(person);
          		if (flag == 1) {
          			return "success";
          		} else {
          			return "fail";
          		}
          	}
          	public String searchPerson() {
          		person = personDAO.getPerson(id);
          		if (person != null) {
          			return "success";
          		} else {
          			return "fail";
          		}
          	}
          	public Person getPerson() {
          		return person;
          	}
          	public void setPerson(Person person) {
          		this.person = person;
          	}
          	public int getId() {
          		return id;
          	}
          	public void setId(int id) {
          		this.id = id;
          	}
          	public PersonDAO getPersonDAO() {
          		return personDAO;
          	}
          	@Resource(name = "personDAO")
          	public void setPersonDAO(PersonDAO personDAO) {
          		this.personDAO = personDAO;
          	}
          }
          

            

          差不多就是這樣了,這是封裝了后代的代碼沒有前臺的展示,不過Junit全部測試通過了。

          posted on 2010-12-27 22:00 王康 閱讀(830) 評論(1)  編輯  收藏

          Feedback

          # re: Struts2+Hibernate+Spring環境的搭建【SSH搭建】!! 2012-11-24 08:10 吳宏偉
          博主 能不能把HibernateUtil這個類貼出來啊   回復  更多評論
            


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 武平县| 九龙城区| 岳普湖县| 清镇市| 龙口市| 白山市| 垦利县| 都兰县| 酉阳| 合肥市| 夏津县| 奇台县| 岚皋县| 志丹县| 荔波县| 信阳市| 武夷山市| 富锦市| 家居| 中西区| 阳泉市| 莫力| 宁远县| 隆化县| 甘孜县| 调兵山市| 昭苏县| 瑞昌市| 黄陵县| 金门县| 全州县| 大庆市| 德保县| 赞皇县| 乐昌市| 河源市| 奇台县| 太白县| 元氏县| 吴忠市| 石柱|