標籤:des http io os ar 使用 java for sp
Sprin2.5+Hibernate3.3+Struts2.0.11整合
1.添加jar檔案
Hibernate3.3核心安裝包下的
/-----------------------------------/
hibernate3.jar
lib\required\*.jar
lib\optional\ehcache-1.2.3.jar
hibernate註解安裝包下的
lib\test\slf4j-log4j12.jar
/-----------------------------------/
Spring安裝包下的
/-----------------------------------/
dist\spring.jar
dist\modules\spring-webmvc-struts.jar
lib\jakaarte-commons\commons-logging.jar、commons-dbcp.jar、commons-pool.jar
lib\aspectj\aspectjweaver.jar 、 aspectjrt.jar
lib\cglib\cglib-nodep-2.1.3.jar
lib\j2ee\common-annoutations.jar
lib\log4j\log4j-1.2.15.jar
/------------------------------------/
資料庫驅動
2. 配置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/tx
http://www.springframework.org/schema/tx/spring-tx-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">
<!--匯入外部properties -->
<context:property-placeholder location="classpath:jdbc.properties" />
<!--配置資料來源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${driverClassName}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
<!--串連池啟動時的初始值 -->
<property name="initialSize" value="${initialSize}" />
<!--串連池的最大值 -->
<property name="maxActive" value="${maxActive}" />
<!--最大空閑值,當經過一個高峰時間後,串連池可以慢慢將已經用不到的串連慢慢釋 放一部分一直減少到maxIdle為止 -->
<property name="maxIdle" value="${maxIdle}" />
<!--最小空閑值,當經閒置串連邵誼閥值時,串連池就會申請一些串連, 以免洪峰來時來不及申請 -->
<property name="minIdle" value="${minIdle}" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>cn/soldier/bean/Person.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<!-- 指定資料庫方言 -->
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLInnoDBDialect
</prop>
<!-- 是否根據需要每次自動建立資料庫 -->
<prop key="hibernate.hbm2ddl.auto">update</prop>
<!-- 顯示Hibernate持久化操作所產生的SQL -->
<prop key="hibernate.show_sql">true</prop>
<!-- 將SQL指令碼進行格式化後再輸出 -->
<prop key="hibernate.format_sql">false</prop>
<!-- <prop key="hibernate.cache.use_second_level_cache">true</prop> -->
<!-- <prop key="hibernate.cache.use_query_cache">true</prop> -->
<!-- <prop key="hibernate.provider_class">org.hibernate.cache.EhCacheProvider</prop> -->
</props>
</property>
</bean>
<!--配置交易管理員 -->
<bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!--啟用@Transaction註解的支援- -->
<tx:annotation-driven transaction-manager="txManager" />
<!--使用field方法注入依賴對象 -->
<context:annotation-config />
<!-- -->
<bean id="personService" class="cn.soldier.service.impl.PersonServiceBean"></bean>
</beans>
3.建立實體bean Person
package cn.soldier.bean;
Person.java
public class Person {
private Long id;
private String name;
public Person() {
}
public Person(String name) {
this.name = name;
}
public Person(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
return "Person [id=" + id + " name=" + name + "]";
}
}
4.建立對應的資料庫映射
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">
<hibernate-mapping package="cn.soldier.bean">
<class name="Person" table="person">
<id name="id">
<generator class="native" />
</id>
<property name="name" />
</class>
</hibernate-mapping>
5.建立訪問Person實體的Service介面
package cn.soldier.service;
import java.util.List;
import cn.soldier.bean.Person;
public interface PersonService {
public abstract void save(Person person);
public abstract void update(Person person);
public abstract void delete(Long id);
public abstract Person getPerson(Long id);
public abstract List<Person> getPersons();
}
6.建立訪問Person實體的Service實現方法
package cn.soldier.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.soldier.bean.Person;
import cn.soldier.service.PersonService;
@Transactional //啟用交易管理
public class PersonServiceBean implements PersonService {
@Resource//使用filed注入SessionFactory對象
SessionFactory sessionFactory;
public void save(Person person) {
// 得到容器裡面正在被Transaction管理的Session
// 如果使用opeSession(),獲得的Session對象是不受Transaction管理的。
Session session = (Session) sessionFactory.getCurrentSession();
session.persist(person);
}
public void update(Person person) {
sessionFactory.getCurrentSession().merge(person);// SaveOrUpdate
}
public void delete(Long id) {
// load方法效能最佳,因為get方法有一個資料裝配的過程
sessionFactory.getCurrentSession().delete(
sessionFactory.getCurrentSession().load(Person.class, id));
}
@Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)// 不啟用交易管理,唯讀
public Person getPerson(Long id) {
return (Person) sessionFactory.getCurrentSession()
.get(Person.class, id);
}
@Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
@SuppressWarnings("unchecked")
// 終止警告
public List<Person> getPersons() {
return sessionFactory.getCurrentSession().createQuery("From Person").list();
}
}
7.測試開發好的PersonServiceBean
package junit.test;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.soldier.bean.Person;
import cn.soldier.service.PersonService;
public class PersonServiceBeanTest {
private static PersonService personService;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
try {
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"beans.xml");
personService = (PersonService) ctx.getBean("personService");
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testSave() {
for (int i = 0; i <10; i++) {
Person person = new Person("逗比---"+i+"---號");
personService.save(person);
}
}
@Test
public void testUpdate() {
Person person = personService.getPerson(1L);
person.setName("逗比2號");
personService.update(person);
System.out.println(personService.getPerson(1L));
}
@Test
public void testDelete() {
personService.delete(2L);
}
@Test
public void testGetPersons() {
for (Person person : personService.getPersons()) {
System.out.println(person);
}
}
}
/*******************************************以上步驟整合了Spring+Hibernate****************************************************/
a.添加jar包
commons-beanutils-1.6.jar
commons-chain-1.1.jar
commons-logging-1.0.4.jar
commons-logging-api-1.1.jar
commons-validator-1.3.0.jar
freemarker-2.3.8.jar
ognl-2.6.11.jar
oro-2.0.8.jar
struts2-core-2.0.11.jar
struts2-spring-plugin-2.0.11.jar
struts-core-1.3.5.jar
tiles-api-2.0.4.jar
tiles-core-2.0.4.jar
tiles-jsp-2.0.4.jar
xwork-2.0.4.jar
2.配置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">
<!--在web容器中執行個體化Spring容器 -->
<!--指定spring的設定檔,預設是從web根目錄下尋找設定檔。可以通過spring提供的classpath:首碼指定從類路徑下尋找 -->
<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>
<!--在web容器中配置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>
3.配置classpath下的 struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<!-- 指定Web應用的預設編碼集,相當於調用 HttpServletRequest的setCharacterEncoding方法 -->
<constant name="struts.i18n.encoding" value="UTF-8" />
<!-- 該 屬性指定需要Struts2處理的請求尾碼,該屬性的預設值是action,即 所有匹配*.action的請求都由Struts 2處理。如
果使用者需要指定多個請求尾碼,則多個尾碼之間以英文逗號(,)隔開 -->
<constant name="struts.action.extension" value="action" />
<!-- 設 置瀏覽器是否緩衝靜態內容,預設值為true(生產環境下使用),開發階段最好 關閉 -->
<constant name="struts.serve.static.browserCache " value="false" />
<!-- 當 struts的設定檔修改後,系統是否自動重新載入該檔案,預設值為false(生 產環境下使用),開發階段最好開啟 -->
<constant name="struts.configuration.xml.reload" value="true" />
<!-- 開 發模式下使用,這樣可以列印出更詳細的錯誤資訊 -->
<constant name="struts.devMode" value="true" />
<!-- 默 認的視圖主題 -->
<constant name="struts.ui.theme" value="simple" />
<!-- 該 屬性指定Struts 2中的action由Spring容器創 建 -->
<constant name="struts.objectFactory" value="spring" />
<package name="person" namespace="/person" extends="struts-default">
<global-results>
<result name="message">/WEB-INF/page/message.jsp</result>
</global-results>
<action name="action_*" class="personList" method="{1}">
<result name="list">/WEB-INF/page/list.jsp</result>
<result name="add">/WEB-INF/page/add.jsp</result>
</action>
</package>
</struts>
4.配置beans.xml
<bean id="personList" class="cn.soldier.web.PersonAction"></bean>
5.添加 list.jap
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%@ taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<title>人員列表</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<s:iterator value="persons">
<s:property value="id" />----<s:property value="name" /><br />
</s:iterator>
<body>
</body>
</html>
6.建立 PersonAction.java
package cn.soldier.web;
import java.util.List;
import javax.annotation.Resource;
import cn.soldier.bean.Person;
import cn.soldier.service.PersonService;
public class PersonAction {
@Resource
PersonService personService;
private String message;
private List<Person> persons;
private Person person;// 負責接收form表單的參數
public String list() {
this.persons = personService.getPersons();
return "list";
}
public String add() {
personService.save(this.person);
this.message = "添加成功";
return "message";
}
public String addUI() {
return "add";
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<Person> getPersons() {
return persons;
}
public void setPersons(List<Person> persons) {
this.persons = persons;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
}
7.測試
http://localhost:8080/SSH2/person/action_list.action
8.添加 add.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>人員添加</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<s:form action="action_add" method="post" namespace="/person">
名稱<s:textfield name="person.name"></s:textfield>
<input type="submit" value="提交" />
</s:form>
</body>
</html>
9.添加message.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP ‘message‘ starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<s:property value="message"/>
</body>
</html>
10.測試
http://localhost:8080/SSH2/person/action_addUI.action
Sprin2.5+Hibernate3.3+Struts2.0.11整合