spring2.5整合hibernate3.0整合Struts

首先:这是spring framework+hibernate+struts集成,spring主要用于aop和ioc,hibernate主要是用于持久层,struts主要是用于mvc。

同时关于springMVC和spring,这两个不是一个概念, springMVC从名字来看,就知道这是一个mvc框架,它和struts是一个层次的,springMVC有自己的类hibernate的存储持久化模块,也支持集成hibernate来完成存储。

项目结构图:

spring2.5整合hibernate3.0整合Struts

 所需jar包:

spring2.5整合hibernate3.0整合Struts

spring2.5整合hibernate3.0整合Struts

一、定义一个Bean,person.java

 package cn.itcast.bean;

 public class Person {
private Integer id;
private String name; public Person() {} public Person(String name) {
this.name = name;
} public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

二、定义一个接口,PersonService 

 package cn.itcast.Service;

 import java.util.List;

 import cn.itcast.bean.Person;

 public interface PersonService {

     public abstract void save(Person person);

     public abstract void update(Person person);

     public abstract Person getPerson(Integer personId);

     public abstract void delete(Integer personId);

     public abstract List<Person> getPersons();

 }

三、定义接口的实现类 PersonServiceBean 

 package cn.itcast.Service.Impl;

 import java.util.List;

 import javax.annotation.Resource;

 import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional; import cn.itcast.Service.PersonService;
import cn.itcast.bean.Person;
@Transactional
public class PersonServiceBean implements PersonService {
@Resource
private SessionFactory sessionFactory; @Override
public void save(Person person){
//取被spring容器管理的session
sessionFactory.getCurrentSession().persist(person);
} @Override
public void update(Person person){
sessionFactory.getCurrentSession().merge(person);
} @Transactional(propagation = Propagation.NOT_SUPPORTED,readOnly = true)
@Override
public Person getPerson(Integer personId){
return (Person) sessionFactory.getCurrentSession().get(Person.class, personId); } @Override
public void delete(Integer personId){
sessionFactory.getCurrentSession().delete(sessionFactory.getCurrentSession().load(Person.class, personId));
} @Transactional(propagation =Propagation.NOT_SUPPORTED,readOnly = true)
@SuppressWarnings("unchecked")
@Override
public List<Person> getPersons(){
return sessionFactory.getCurrentSession().createQuery("from Person").list(); }
}

四、配置文件beans.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: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-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-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"> <!-- <context:property-placeholder location="classpath:jdbc.properties"/> -->
<context:annotation-config/>
<!-- 配置dataSource -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:@192.168.1.10:1521:orcl"/>
<property name="username" value="tsrescue"/>
<property name="password" value="123456"/>
<!-- 连接池启动时的初始值 -->
<property name="initialSize" value="1"/>
<!-- 连接池的最大值 -->
<property name="maxActive" value="500"/>
<!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
<property name="maxIdle" value="2"/>
<!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
<property name="minIdle" value="1"/>
</bean>
<!-- 配置sessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingResources">
<list>
<value>cn/itcast/bean/Person.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props> </property>
</bean>
<!-- spring提供的针对hibernate的事务管理器 -->
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- 基于注解的方式声明事务 -->
<tx:annotation-driven transaction-manager="txManager"/>
<bean id = "personService" class="cn.itcast.Service.Impl.PersonServiceBean"/>
</beans>

五,定义Person.hbm.xml

 <?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2016-6-1 10:08:44 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping package="cn.itcast.bean">
<class name="Person" table="person">
<id name="id">
<generator class="native" />
</id>
<property name="name"/>
</class>
</hibernate-mapping>

六、定义测试类 PersonServiceBeanTest 

 package cn.itcast.Service.Impl;

 import static org.junit.Assert.*;

 import java.util.List;

 import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import cn.itcast.Service.PersonService;
import cn.itcast.bean.Person; public class PersonServiceBeanTest {
private static PersonService ps;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
try {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
ps = (PersonService) ctx.getBean("personService");
} catch (Exception e) {
e.printStackTrace();
}
} @Test
public void testSave() {
for(int i = 1;i<=10;i++){
ps.save(new Person("小明"+i));
}
} @Test
public void testUpdate() {
Person person = ps.getPerson(1);
person.setName("小明修改版");
ps.update(person);
} @Test
public void testGetPerson() {
Person p = ps.getPerson(1);
System.out.println(p.getName());
} @Test
public void testDelete() {
ps.delete(3);
} @Test
public void testGetPersons() {
List<Person> list = ps.getPersons();
for (Person person : list) {
System.out.println(person.getName());
}
} }

以上实现了对数据库的操作,下面通过整合Struts来实现将数据传递到页面

一、首先定义一个action,PersonAction 继承Action

 package cn.itcast.web.action;

 import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
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 org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils; import cn.itcast.Service.PersonService; public class PersonAction extends Action { @Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(this.getServlet().getServletContext());
PersonService personService = (PersonService) ctx.getBean("personService");
request.setAttribute("persons", personService.getPersons());
return mapping.findForward("list"); }
}

二、定义struts-config.xml

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
"http://struts.apache.org/dtds/struts-config_1_3.dtd">
<struts-config>
<action-mappings>
<action path = "/person/list" type = "cn.itcast.web.action.PersonAction"
validate = "false">
<forward name = "list" path = "/WEB-INF/page/personlist.jsp"/>
</action>
</action-mappings>
</struts-config>

三、定义web.xml

 <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:beans.xml</param-value>
</context-param>
<!-- 对Spring容器进行实例化 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <servlet>
<servlet-name>struts</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>struts</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

四、定义一个jsp页面,用来显示数据。

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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=UTF-8">
<title>人员列表</title>
</head>
<body>
<c:forEach items="${persons }" var="person">
${person.id },${person.name }<br>
</c:forEach>
</body>
</html>

好了,至此简单的ssh框架整合完毕!

当然,上面的方案存在小小的缺陷,action每次取的spring容器实例都要采用这种方式:

WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(this.getServlet().getServletContext()); PersonService personService = (PersonService) ctx.getBean("personService"); 

所以我们不如采用spring依赖注入的方式,将这个对象注入进来,

首先在beans.xml中注入PersonAction,

注意:1、确保struts-config.xml中action的path属性和bean名称相同。

<bean name = "/person/list" class="cn.itcast.web.action.PersonAction"/>

2、在struts-config.xml中定义一个控制器如下:

 <controller>
<set-property value="processorClass" value = "org.springframework.web.struts.DelegatingRequestProcessor"/>
</controller>

3、在PersonAction.java中注入PersonService即可!

 package cn.itcast.web.action;

 import javax.annotation.Resource;
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 cn.itcast.Service.PersonService; public class PersonAction extends Action {
@Resource
private PersonService personService; @Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
// WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(this.getServlet().getServletContext());
// PersonService personService = (PersonService) ctx.getBean("personService"); request.setAttribute("persons", personService.getPersons());
return mapping.findForward("list"); }
}
上一篇:php使用flock阻塞写入文件和非阻塞写入文件的实例讲解


下一篇:60.纯 CSS 创作一块乐高积木