一、建立數(shù)據(jù)庫聯(lián)結(jié)池
二、建立測(cè)試數(shù)據(jù)庫
三、建立Hibernate配置
四、把數(shù)據(jù)庫的表映射為類
五、模板中的包定義
六、設(shè)計(jì)模式:單例
七、設(shè)計(jì)模式:門面
八、設(shè)計(jì)模式:DAO
九、設(shè)計(jì)模式:MVC
十、自定義標(biāo)簽
十一、解決漢字編碼問題
一、建立數(shù)據(jù)庫聯(lián)結(jié)池
1.把數(shù)據(jù)庫驅(qū)動(dòng)程序拷入Tomcat5.0的common\lib目錄下.
如:oracle9i拷貝ojdbc14.jar
2.修改TOMCAT配置文件conf\server.xml.在</host>之前加入如下代碼:
<Context path="/demo" docBase="F:\j_work\working\demo\demo" debug="5" reloadable="true" crossContext="true">
<Logger className="org.apache.catalina.logger.FileLogger" prefix="localhost_DBTest_log." suffix=".txt" timestamp="true"/>
<Resource name="jdbc/demo" auth="Container" type="javax.sql.DataSource"/>
<ResourceParams name="jdbc/demo">
<parameter>
<name>factory</name>
<value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
</parameter>
<parameter>
<name>driverClassName</name>
<value>oracle.jdbc.driver.OracleDriver</value>
</parameter>
<parameter>
<name>url</name>
<value>jdbc:oracle:thin:@192.168.3.200:1521:demo</value>
</parameter>
<parameter>
<name>username</name>
<value>demo</value>
</parameter>
<parameter>
<name>password</name>
<value>demo</value>
</parameter>
<parameter>
<name>maxActive</name>
<value>20</value>
</parameter>
<parameter>
<name>maxIdle</name>
<value>10</value>
</parameter>
<parameter>
<name>maxWait</name>
<value>-1</value>
</parameter>
</ResourceParams>
</Context>
二、建立測(cè)試數(shù)據(jù)庫
1.建立數(shù)據(jù)庫用戶名 demo 密碼 demo
2.建立測(cè)試表
建立測(cè)試表 demo
字段說明
id char(100) 主鍵
name varchar2(50) 名字
image_id number(10) 圖片id
system_date date 系統(tǒng)日期
user_date date 錄入日期
建立圖片索引表 image
字段說明
id char(100) 主鍵
title varchar2(50) 圖片標(biāo)題
message varchar2(2000) 圖片信息
original_image_path varchar(200) 原始圖片保存路徑
small _image_path varchar(200) 小圖片保存路徑
image_id number(10) 圖片id
system_date date 系統(tǒng)日期
id索引表 Singleton_Id
字段說明
id char(100) 主鍵
name varchar2(50) 索引名(需要為此字段建索引)
value number(10) 索引id
三、建立Hibernate配置
1.拷貝Oracle9i數(shù)據(jù)庫驅(qū)動(dòng)程序ojdbc14.jar到JBUILDER9安裝目錄的LIB目錄下.用JBUILDER9.0建立PROJECT工程.
2.把如下hibernate-2.0.3必須的庫文件包含在工程中.
hibernate2.jar
commons-beanutils.jar
commons-collections.jar
commons-dbcp.jar
commons-lang.jar
commons-logging.jar
commons-pool.jar
dom4j.jar
cglib-asm.jar
connector.jar
3.建立 hibernate.cfg.xml文件,并拷到SRC目錄
<?xml version=‘1.0‘ encoding=‘utf-8‘?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.datasource">java:comp/env/jdbc/demo</property>
<property name="show_sql">true</property>
<property name="use_outer_join">true</property>
<property name="dialect">net.sf.hibernate.dialect.Oracle9Dialect</property>
<!-- Mapping files -->
<!--mapping resource="com\kmtava\qtmis\jdo\TCzy.hbm.xml"/-->
</session-factory>
</hibernate-configuration>
四、把數(shù)據(jù)庫的表映射為類
下載 hibernate-extensions 壓縮包. 修改 setenv.bat文件中的環(huán)境變量.主要修改Hibernate的目錄和數(shù)據(jù)庫驅(qū)動(dòng)程序文件名.
例如:
@echo off
rem -------------------------------------------------------------------
rem Setup environment for hibernate tools
rem -------------------------------------------------------------------
set JDBC_DRIVER=..\..\..\lib\ojdbc14.jar
set HIBERNATE_HOME=..\..\..\hibernate-2.0.3
set CORELIB=%HIBERNATE_HOME%\lib
set LIB=..\lib
set PROPS=%HIBERNATE_HOME%\src
set CP=%JDBC_DRIVER%;%PROPS%;%HIBERNATE_HOME%\hibernate2.jar;%CORELIB%\commons-logging.jar;%CORELIB%\commons-collections.jar;
%CORELIB%\commons-lang.jar;%CORELIB%\cglib.jar;%CORELIB%\dom4j.jar;%CORELIB%\odmg.jar;%CORELIB%\xml-apis.jar;%CORELIB%\xerces.jar;
%CORELIB%\xalan.jar;%LIB%\jdom.jar;%LIB%\..\hibernate-tools.jar
運(yùn)行ddl2hbm.bat, 設(shè)置參數(shù)如下:
[ CONNECTION ]
DRIVER CLASS : oracle.jdbc.driver.OracleDriver (org.gjt.mm.mysql.Driver)
CONNECTION URL: jdbc:oracle:thin:@192.168.3.200:1521:demo (jdbc:mysql://localhost/authority)
USER: demo
PASSWORD: demo
[ MAPPING ]
KEY FIELD : id
SCHEMAEXPORT : uuid.hex
[ CODE ]
PACKAGE NAME: com.company.demo.jdo
[ OUTPUT ]
F:\j_work\working\demo\src
其它的用默認(rèn)值,點(diǎn)[TABLES]的tables..選擇表,程序生成類和xml
生成的文件如下:
(1)image.java
package com.company.demo.jdo;
import java.io.Serializable;
import java.util.Date;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
/** @author Hibernate CodeGenerator */
public class Image implements Serializable {
/** identifier field */
private String id;
/** nullable persistent field */
private String title;
/** nullable persistent field */
private String message;
/** nullable persistent field */
private String originalImagePath;
/** nullable persistent field */
private String smallImagePath;
/** nullable persistent field */
private long imageId;
/** nullable persistent field */
private Date systemDate;
/** full constructor */
public Image(String title, String message, String originalImagePath, String smallImagePath, long imageId, Date systemDate) {
this.title = title;
this.message = message;
this.originalImagePath = originalImagePath;
this.smallImagePath = smallImagePath;
this.imageId = imageId;
this.systemDate = systemDate;
}
/** default constructor */
public Image() {
}
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public String getMessage() {
return this.message;
}
public void setMessage(String message) {
this.message = message;
}
public String getOriginalImagePath() {
return this.originalImagePath;
}
public void setOriginalImagePath(String originalImagePath) {
this.originalImagePath = originalImagePath;
}
public String getSmallImagePath() {
return this.smallImagePath;
}
public void setSmallImagePath(String smallImagePath) {
this.smallImagePath = smallImagePath;
}
public long getImageId() {
return this.imageId;
}
public void setImageId(long imageId) {
this.imageId = imageId;
}
public Date getSystemDate() {
return this.systemDate;
}
public void setSystemDate(Date systemDate) {
this.systemDate = systemDate;
}
public String toString() {
return new ToStringBuilder(this)
.append("id", getId())
.toString();
}
public boolean equals(Object other) {
if ( !(other instanceof Image) ) return false;
Image castOther = (Image) other;
return new EqualsBuilder()
.append(this.getId(), castOther.getId())
.isEquals();
}
public int hashCode() {
return new HashCodeBuilder()
.append(getId())
.toHashCode();
}
}
(2)Image.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 2.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping>
<class name="com.company.demo.jdo.Image" schema="DEMO" table="IMAGE">
<id column="ID" name="id" type="string">
<generator class="uuid.hex"/>
</id>
<property column="TITLE" length="50" name="title" type="string"/>
<property column="MESSAGE" length="2000" name="message" type="string"/>
<property column="ORIGINAL_IMAGE_PATH" length="200" name="originalImagePath" type="string"/>
<property column="SMALL_IMAGE_PATH" length="200" name="smallImagePath" type="string"/>
<property column="IMAGE_ID" length="10" name="imageId" type="long"/>
<property column="SYSTEM_DATE" length="7" name="systemDate" type="timestamp"/>
</class>
</hibernate-mapping>
其它生成的文件略!
五、模板中的包定義
com.company.demo.dataModule 數(shù)據(jù)模型
com.company.demo.dao DAO模型
com.company.demo.exception 異常
com.company.demo.jdo hibernate類映射
com.company.demo.start 啟動(dòng)JSP服務(wù)時(shí)加載的類
com.company.demo.tags 自定義標(biāo)簽類
com.company.demo.thread 線程類
com.company.demo.util 工具類
com.company.demo.web Struts類
com.company.demo.facade Facade調(diào)用的類
六、設(shè)計(jì)模式:單例
1.數(shù)據(jù)模型
接口(Datamodule.java)
package com.company.demo.datamodule;
package com.company.demo.datamodule;
import net.sf.hibernate.Session;
import net.sf.hibernate.Transaction;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.cfg.Configuration;
/**
* <p>Title: Struts+Hibernate開發(fā)模板</p>
* <p>Description: 通用開發(fā)模板</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: 優(yōu)勢(shì)科技</p>
* @author 段洪杰
* @version 1.0
*/
public interface DataModule {
public SessionFactory getSessionFactory();
}
數(shù)據(jù)模型 (DatamoduleImpl.java)
package com.company.demo.datamodule;
/**
* <p>Title: Struts+Hibernate開發(fā)模板</p>
* <p>Description: 通用開發(fā)模板</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: 優(yōu)勢(shì)科技</p>
* @author 段洪杰
* @version 1.0
*/
import net.sf.hibernate.Session;
import net.sf.hibernate.Transaction;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.cfg.Configuration;
/**
* 建立 SessionFactory
*/
public class DataModuleImpl implements DataModule {
private SessionFactory sessionFactory;
public DataModuleImpl() throws HibernateException {
sessionFactory=new Configuration().configure().buildSessionFactory();
}
/**
* 從dataModule中取得 SessionFactory
*/
public SessionFactory getSessionFactory(){
return this.sessionFactory;
}
}
2.產(chǎn)生唯一ID的父類
接口 (SingletonIdDAO.java)
package com.company.demo.dao;
/**
* <p>Title: Struts+Hibernate開發(fā)模板</p>
* <p>Description: 通用開發(fā)模板</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: 優(yōu)勢(shì)科技</p>
* @author 段洪杰
* @version 1.0
*/
public interface SingletonIdDAO {
}
ID父類 (SingletonIdDAOImpl.java)
package com.company.demo.dao;
import java.util.List;
import com.company.demo.datamodule.*;
import com.company.demo.jdo.SingletonId;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.Transaction;
import net.sf.hibernate.Query;
/**
* 產(chǎn)生唯一的ID
*
* 數(shù)據(jù)庫結(jié)構(gòu)(ORACLE9i):
* 表名 SINGLETON_ID
* 字段 id(char) name varchar2(50) value number(10.0)
*
*
* <p>Title: Struts+Hibernate開發(fā)模板</p>
* <p>Description: 通用開發(fā)模板</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: 優(yōu)勢(shì)科技</p>
* @author 段洪杰
* @version 1.0
*
*
*/
public class SingletonIdDAOImpl implements SingletonIdDAO{
private SessionFactory sessionFactory;
private DataModule dataModule;
/**
* 設(shè)數(shù)據(jù)模型
*/
public void setDataModule(DataModule dataModule){
this.dataModule=dataModule;
this.sessionFactory=dataModule.getSessionFactory();
}
////////////////以下是業(yè)務(wù)邏輯////////////////////
private SingletonId findByName(String name) throws HibernateException,Exception {
Transaction transaction = null;
SingletonId singletonId=new SingletonId();
Session session=sessionFactory.openSession();
String queryString = "select g from SingletonId as g where g.name = :name order by g.value desc";
try{
transaction = session.beginTransaction();
Query query = session.createQuery(queryString);
query.setString("name",name);
// q.setFirstResult(20000);
//q.setMaxResults(100);
query.setMaxResults(1);
List list=query.list();
singletonId=(SingletonId)list.get(0);
transaction.commit();
}
catch(Exception ex){
if ( transaction!=null ){
transaction.rollback();
}
//throw ex;
}finally{
session.close();
}
return singletonId;
}
/** 取得value
* @param name 產(chǎn)唯一ID的類型名稱
* @return value
* @throws HibernateException
*/
protected long getValue(String name) throws HibernateException,Exception {
SingletonId singletonId=findByName(name);
return singletonId.getValue();
}
/** 設(shè)置value
* @param name 產(chǎn)唯一ID的類型名稱
* @throws HibernateException
*/
protected void setValue(String name) throws HibernateException,Exception {
Session session=sessionFactory.openSession();
SingletonId singletonId=findByName(name);
singletonId.setName(name);
singletonId.setValue(singletonId.getValue()+1);
Transaction transaction = null;
try{
transaction = session.beginTransaction();
session.saveOrUpdate(singletonId);
transaction.commit();
}catch(HibernateException he){
if ( transaction!=null ){
transaction.rollback();
}
throw he;
}finally{
session.close();
}
}
}
3.單例圖片ID類(ImageSingletonId.java)
package com.company.demo.dao.count;
import net.sf.hibernate.HibernateException;
import com.company.demo.dao.SingletonIdDAOImpl;
import com.company.demo.datamodule.DataModule;
/**
* <p>Title: Struts+Hibernate開發(fā)模板</p>
* <p>Description: 通用開發(fā)模板</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: 優(yōu)勢(shì)科技</p>
* @author 段洪杰
* @version 1.0
*/
public class ImageSingletonId extends SingletonIdDAOImpl{
private static ImageSingletonId imageSingletonId = null;
/**
* 構(gòu)造函數(shù)私有
*/
private ImageSingletonId(){
}
/**
* 靜態(tài)工廠模式,取得ImageSingletonId實(shí)例
*/
public static synchronized ImageSingletonId getInstance() {
if (imageSingletonId==null)
{
imageSingletonId=new ImageSingletonId();
}
return imageSingletonId;
}
/**
* 取圖形唯一ID
*/
public synchronized long getImageValue() throws HibernateException,Exception {
long value;
setValue("image");
value=getValue("image");
return value;
}
}
4.圖片ID測(cè)試文件(TestImageSingletonId.jsp)
<%@ page contentType="text/html; charset=gb2312" %>
<%@ page import="net.sf.hibernate.*" %>
<%@ page import="net.sf.hibernate.cfg.*" %>
<%@ page import="com.company.demo.datamodule.*" %>
<%@ page import="com.company.demo.dao.count.*" %>
<%!
DataModule dataModule;
ImageSingletonId imageSingletonId;
%>
<%
try{
imageSingletonId=ImageSingletonId.getInstance();
imageSingletonId.setDataModule(new DataModuleImpl());
}
catch(Exception ex)
{
ex.toString();
}
for(int i=0;i<100;i++){
out.print("測(cè)試..........<BR>");
out.print(imageSingletonId.getImageValue());
out.print("----------------<BR>");
}
%>
5.單例記數(shù)器ID類(MainPageSingletonId.java)
package com.company.demo.dao.count;
import net.sf.hibernate.HibernateException;
import com.company.demo.dao.SingletonIdDAOImpl;
import com.company.demo.datamodule.DataModule;
/**
* <p>Title: Struts+Hibernate開發(fā)模板</p>
* <p>Description: 通用開發(fā)模板</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: 優(yōu)勢(shì)科技</p>
* @author 段洪杰
* @version 1.0
*/
public class MainPageSingletonId extends SingletonIdDAOImpl{
private static MainPageSingletonId mainPageSingletonId = null;
/**
* 構(gòu)造函數(shù)私有
*/
private MainPageSingletonId(){
}
/**
* 靜態(tài)工廠模式,取得MainPageSingletonId實(shí)例
*/
public static synchronized MainPageSingletonId getInstance() {
if (mainPageSingletonId==null)
{
mainPageSingletonId=new MainPageSingletonId();
}
return mainPageSingletonId;
}
/**
* 取唯一ID
*/
public synchronized long getMainPageValue() throws HibernateException,Exception {
long value;
setValue("mainPage");
value=getValue("mainPage");
return value;
}
}
6.記數(shù)ID測(cè)試文件(TestMainPageSingletonId.jsp)
<%@ page contentType="text/html; charset=gb2312" %>
<%@ page import="net.sf.hibernate.*" %>
<%@ page import="net.sf.hibernate.cfg.*" %>
<%@ page import="com.company.demo.datamodule.*" %>
<%@ page import="com.company.demo.dao.count.MainPageSingletonId" %>
<%!
DataModule dataModule;
MainPageSingletonId mainPageSingletonId;
%>
<%
try{
mainPageSingletonId=MainPageSingletonId.getInstance();
mainPageSingletonId.setDataModule(new DataModuleImpl());
}
catch(Exception ex)
{
ex.toString();
}
for(int i=0;i<100;i++){
out.print("測(cè)試..........<BR>");
out.print(mainPageSingletonId.getMainPageValue());
out.print("----------------<BR>");
}
%>
7.綜合單例測(cè)試(略)
七、設(shè)計(jì)模式:門面
1.在JSP中調(diào)"Session Facade"類
在JSP文件中插入下列標(biāo)簽:
<jsp:useBean id="sessionBean" scope="session" class="com.company.demo.web.SessionBean" />
2.SessionBean類
package com.company.demo.web;
import com.company.demo.datamodule.*;
import com.company.demo.thread.*;
import com.company.demo.facade.*;
/**
* <p>Title: Struts+Hibernate開發(fā)模板</p>
* <p>Description: 通用開發(fā)模板</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: 優(yōu)勢(shì)科技</p>
* @author 段洪杰
* @version 1.0
*/
public class SessionBean {
private DataModule dataModule;//數(shù)據(jù)模型
private Auth auth; //登錄的用戶信息
private Business business; //系統(tǒng)中的業(yè)務(wù)邏輯主線
private Line line; //保存模塊中的關(guān)聯(lián)狀態(tài)
/**
* 構(gòu)函數(shù),初始化業(yè)務(wù)邏輯中的類(單例)
*/
public SessionBean(){
try {
dataModule=SessionBeanSingletonFactory.getDataModule();
auth=SessionBeanSingletonFactory.getAuth();
business=SessionBeanSingletonFactory.getBusiness();
line=SessionBeanSingletonFactory.getLine();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* 門面模式調(diào)用的公共應(yīng)用模塊
* @return Utility
*/
public Utility getUtility() {
return SessionBeanFactory.getUtility();
}
}
3.SessionBeanFactory類
package com.company.demo.web; import com.company.demo.datamodule.*;
import com.company.demo.thread.*;
import com.company.demo.facade.*;
import net.sf.hibernate.HibernateException;
/**
* SessionBean門面模式的抽象工廠類
* <p>Title: Struts+Hibernate開發(fā)模板</p>
* <p>Description: 通用開發(fā)模板</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: 優(yōu)勢(shì)科技</p>
* @author 段洪杰
* @version 1.0
*/
public class SessionBeanFactory {
/**
* 生成業(yè)務(wù)邏輯狀態(tài)實(shí)例(facade)
* @return LineImpl
* @throws HibernateException
*/
private SessionBeanFactory(){}
public final static Utility getUtility(){
return new UtilityImpl();
}
}
4.SessionBeanSingletonFactory類
package com.company.demo.web; import com.company.demo.datamodule.*;
import com.company.demo.thread.*;
import com.company.demo.facade.*;
import net.sf.hibernate.HibernateException;
/**
* <p>Title: Struts+Hibernate開發(fā)模板</p>
* <p>Description: 通用開發(fā)模板</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: 優(yōu)勢(shì)科技</p>
* @author 段洪杰
* @version 1.0
*/
public class SessionBeanSingletonFactory {
/**
* 生成用戶認(rèn)證實(shí)例(單例)
* @return AuthImpl
* @throws HibernateException
*/
private SessionBeanSingletonFactory(){}
public final static Auth getAuth() throws HibernateException{
return new AuthImpl();
}
/**
* 生成商務(wù)邏輯實(shí)例(單例)
* @return BusinessImpl
* @throws HibernateException
*/
public final static Business getBusiness() throws HibernateException{
return new BusinessImpl();
}
/**
* 生成數(shù)據(jù)模型實(shí)例(單例)
* @return DataModuleImpl
* @throws HibernateException
*/
public final static DataModule getDataModule() throws HibernateException{
return new DataModuleImpl();
}
/**
* 生成業(yè)務(wù)邏輯狀態(tài)實(shí)例(單例)
* @return LineImpl
* @throws HibernateException
*/
public final static Line getLine() throws HibernateException{
return new LineImpl();
}
}
八、設(shè)計(jì)模式:DAO
使用數(shù)據(jù)訪問對(duì)象(DAO)使我們可以將底層數(shù)據(jù)訪問邏輯與業(yè)務(wù)邏輯分離開。我們構(gòu)建了為每一個(gè)數(shù)據(jù)源提供 GRUD (創(chuàng)建、讀取、更新、刪除)操作的 DAO 類。
下面是一個(gè)數(shù)據(jù)源GRUD(創(chuàng)建)操作的DAO實(shí)例.
1.接口(DemoDAO.java)
package com.company.demo.dao;
import net.sf.hibernate.HibernateException;
import com.company.demo.jdo.Demo;
import com.company.demo.datamodule.*;
/**
* <p>Title: Struts+Hibernate開發(fā)模板</p>
* <p>Description: 通用開發(fā)模板</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: 優(yōu)勢(shì)科技</p>
* @author 段洪杰
* @version 1.0
*/
public interface DemoDAO {
/**設(shè)置數(shù)據(jù)模型**/
public void setDataModule(DataModule dataModule);
/** 建立對(duì)象 **/
public void createDemo(Demo demo) throws HibernateException,Exception;
}
2.抽象工廠(DemoDAOFactory.java)
package com.company.demo.dao;
/**
* <p>Title: Struts+Hibernate開發(fā)模板</p>
* <p>Description: 通用開發(fā)模板</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: 優(yōu)勢(shì)科技</p>
* @author 段洪杰
* @version 1.0
*/
public class DemoDAOFactory {
private DemoDAOFactory()
{ }
public final static DemoDAO getDemoDAO(){
return new DemoDAOImpl();
}
}
3.DAO類(DemoDAOImpl.java)
package com.company.demo.dao;
import java.util.List;
import com.company.demo.datamodule.*;
import com.company.demo.jdo.Demo;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.Transaction;
import net.sf.hibernate.Query;
/**
* <p>Title: Struts+Hibernate開發(fā)模板</p>
* <p>Description: 通用開發(fā)模板</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: 優(yōu)勢(shì)科技</p>
* @author 段洪杰
* @version 1.0
*/
public class DemoDAOImpl implements DemoDAO {
private SessionFactory sessionFactory;
private DataModule dataModule;
/**
* 設(shè)數(shù)據(jù)模型
* @param dataModule
*/
public void setDataModule(DataModule dataModule){
this.dataModule=dataModule;
this.sessionFactory=dataModule.getSessionFactory();
}
/**
* 建立DEMO
* @param demo
* @throws HibernateException
* @throws java.lang.Exception
*/
public void createDemo(Demo demo) throws HibernateException,Exception {
Transaction transaction = null;
Session session=sessionFactory.openSession();
try{
transaction = session.beginTransaction();
session.save(demo);
transaction.commit();
}catch(HibernateException he){
if ( transaction!=null ){
transaction.rollback();
}
throw he;
}finally{
session.close();
}
}
}
九、設(shè)計(jì)模式:MVC
1.表示層(應(yīng)用了template)
JSP文件(template/Basictemplate.jsp)
<%@ page contentType="text/html; charset=gb2312" %>
<%@ taglib uri=‘/WEB-INF/struts-template.tld‘ prefix=‘template‘ %>
<html>
<head>
<title><template:get name=‘title‘/></title>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html;CHARSET=gb2312">
<META HTTP-EQUIV="Content-Language" CONTENT="zh-CN">
<META name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
<META name="keywords" content="extreme programming, extreme projects, design pattern, J2EE, forum, chinese">
<LINK href="default.css" type="text/css" rel="stylesheet">
</head>
<body topmargin=‘0‘>
<table width="95%" border="0" align="center">
<tr>
<td width="17%" rowspan="3">
<!-- START OF NAVBAR -->
<template:get name=‘navbar‘/>
<!-- END OF NAVBAR -->
</td>
<td width="83%" valign="top">
<!-- START OF HEADER -->
<template:get name=‘header‘/>
<!-- END OF HEADER -->
</td>
</tr>
<tr>
<td valign="top">
<!-- START OF CONTENT -->
<template:get name=‘content‘/>
<!--END OF CONTENT -->
</td>
</tr>
<tr>
<td valign="top">
<!-- START OF FOOTER -->
<template:get name=‘footer‘/>
<!-- END OF FOOTER -->
</td>
</tr>
</table>
</body></html>
JSP文件(addDemo.jsp)
<%
/**
* <p>Title: Struts開發(fā)測(cè)試1.0</p>
* <p>Description:項(xiàng)目說明 </p>
* <p>Copyright: Copyright (c) 2003-2008 </p>
* <p>Company:優(yōu)勢(shì)科技 </p>
* @author 段洪杰
* @version 1.0
* @time [2003年10月22日 14時(shí)50分]
**/
%>
<%@page contentType="text/html; charset=gb2312" %>
<%@taglib uri=‘/WEB-INF/struts-template.tld‘ prefix=‘template‘ %>
<template:insert template=‘/template/basicTemplate.jsp‘>
<template:put name=‘title‘ content=‘Struts開發(fā)測(cè)試1.0‘ direct=‘true‘/>
<template:put name=‘navbar‘ content=‘/content/navbar.jsp‘ />
<template:put name=‘header‘ content=‘/content/header.jsp‘ />
<template:put name=‘content‘ content=‘/content/addDemo.jsp‘/>
<template:put name=‘footer‘ content=‘/content/footer.jsp‘ />
</template:insert>
JSP文件(content/addDemo.jsp)
<%
/**
* <p>Title: Struts開發(fā)測(cè)試1.0</p>
* <p>Description:項(xiàng)目說明 </p>
* <p>Copyright: Copyright (c) 2003-2008 </p>
* <p>Company:優(yōu)勢(shì)科技 </p>
* @author 段洪杰
* @version 1.0
* @time [2003年10月22日 14時(shí)50分]
**/
%>
<%@page contentType = "text/html; charset=GB2312" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@taglib uri="/WEB-INF/ImageTag.tld" prefix="image" %>
<%@taglib uri="/WEB-INF/DateTag.tld" prefix="date" %>
<jsp:useBean id="sessionBean" scope="session" class="com.company.demo.web.SessionBean" />
<html:errors/>
<FORM METHOD="post" ACTION="addDemoAction.do" >
<p>名字(name) :
<input name="name" type="text">
</p>
<p>日期(date) :
<date:inputButton type="date" name="userDate"/>
</p>
<p>日期(date) :
<date:inputButton type="datetime" name="userDateTime"/>
</p>
<p>
<image:uploadButton savePath="saveimagepath"/>
</p>
<p>
<input type="submit" name="Submit" value="提交">
<input type="reset" name="Submit2" value="重置">
</p>
</FORM>
控制層(struts-config.xml)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.0//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_0.dtd">
<struts-config>
<form-beans>
<form-bean name="demoActionForm" type="com.company.demo.web.DemoActionForm" />
<form-bean name="imageUploadActionForm" type="com.company.demo.web.ImageUploadActionForm" />
</form-beans>
<global-forwards>
<forward name="unknown-error" path="/error.jsp" />
<forward name="success" path="/success.jsp" />
</global-forwards>
<action-mappings>
<action name="demoActionForm" type="com.company.demo.web.AddDemoAction" input="/addDemo.jsp" scope="request" path="/addDemoAction" />
<action name="imageUploadActionForm" type="com.company.demo.web.ImageUploadAction" input="/content/imageUpload.jsp" scope="request" path="/imageUploadAction" />
</action-mappings>
</struts-config>
文件(DemoActionForm.java)
package com.company.demo.web;
import org.apache.struts.action.*;
import javax.servlet.http.*;
public class DemoActionForm extends ActionForm {
private String name;
private String userDate;
private String userDateTime;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUserDate() {
return userDate;
}
public void setUserDate(String userDate) {
this.userDate = userDate;
}
public String getUserDateTime() {
return userDateTime;
}
public void setUserDateTime(String userDateTime) {
this.userDateTime = userDateTime;
}
public ActionErrors validate(ActionMapping actionMapping, HttpServletRequest httpServletRequest) {
/**@todo: finish this method, this is just the skeleton.*/
return null;
}
public void reset(ActionMapping actionMapping, HttpServletRequest httpServletRequest) {
}
}
應(yīng)用邏輯層(AddDemoAction.java)
package com.company.demo.web;
import org.apache.struts.action.*;
import javax.servlet.http.*;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import com.company.demo.jdo.Demo;
import com.company.demo.dao.DemoDAO;
import com.company.demo.dao.DemoDAOFactory;
import com.company.demo.dao.DemoDAOImpl;
public class AddDemoAction extends Action {
public ActionForward perform(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
/**@todo: complete the business logic here, this is just a skeleton.*/
DemoActionForm demoActionForm = (DemoActionForm) actionForm;
SessionBean sessionBean = (SessionBean) httpServletRequest.getSession().getAttribute("sessionBean");
if (sessionBean == null) {
httpServletRequest.setAttribute("message", "系統(tǒng)超時(shí),請(qǐng)重新登錄!!!");
return actionMapping.findForward("unknown-error");
}
else {
try {
Demo demo = new Demo();
demo.setName(demoActionForm.getName());
DateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd hh:ss:mm");
Date userDateTime = dateTimeFormat.parse(demoActionForm.getUserDateTime());
demo.setSystemDate(userDateTime);
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date userDate = dateFormat.parse(demoActionForm.getUserDate());
demo.setUserDate(userDate);
DemoDAO demoDAO = DemoDAOFactory.getDemoDAO();
demoDAO.setDataModule(sessionBean.getDataModule());
demoDAO.createDemo(demo);
}
catch (Exception ex) {
httpServletRequest.setAttribute("message",ex.toString());
return (actionMapping.findForward("unknown-error"));
}
httpServletRequest.setAttribute("message", "成功!");
return (actionMapping.findForward("success"));
}
}
}
十、自定義標(biāo)簽
1.自定義標(biāo)簽庫(DateTag.tld)
<?xml version="1.0" encoding="GB2312" ?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.2</jspversion>
<shortname>Date Tag Library</shortname>
<info>日期錄入標(biāo)簽庫</info>
<tag>
<name>inputButton</name>
<tagclass>com.company.demo.tags.DateTag</tagclass>
<bodycontent>empty</bodycontent>
<attribute>
<name>name</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>type</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
2.Tag類(DateTag.java)
package com.company.demo.tags; import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import javax.servlet.*;
/**
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: </p>
* @author 段洪杰
* @version 1.0
* 生成日期錄框
*/
public class DateTag extends TagSupport{
String type,name; //類型和參數(shù)名
public void setType(String type)throws JspException {
this.type=type;
}
public void setName(String name)throws JspException {
this.name=name;
}
public int doStartTag() throws JspException {
String string,dialogHeight,dialogWidth,size;
if(type=="date") {
dialogHeight="290";
dialogWidth="240";
size="10";
}
else if(type=="datetime") {
dialogHeight="315";
dialogWidth="240";
size="18";
}
else {
throw new JspTagException("類型參數(shù)錯(cuò)誤,只能選擇date或datetime!");
}
string="<SCRIPT language=javascript>"+
"function selectDate"+name+"(oSource){"+
"window.showModalDialog(‘content/dtpicker.jsp?rn=‘+Math.random(),oSource,‘dialogHeight:"+dialogHeight+"px; dialogWidth: "+dialogWidth+"px;center: Yes; help: No; resizable: No;scroll:No;status: No;‘)"+
"}"+
"</script>"+
"<INPUT readOnly size="+size+" name="+name+
" DataType=\"date\" comparer=\"compareToLastUsedOn\" dateTimeType="+type+">"+
"<IMG src=\"images/select.gif\" width=\"23\" height=\"23\" align=absMiddle"+
" onclick=selectDate"+name+"(document.all(this.sourceIndex-1))> ";
try{
JspWriter out=pageContext.getOut();
out.println(string);
}
catch(Exception ex)
{
throw new JspTagException("程序調(diào)用標(biāo)簽時(shí)出錯(cuò): "+ex.getMessage());
}
return SKIP_BODY;
}
public int doEndTag() throws JspException {
return EVAL_PAGE;
}
}
十一、解決漢字編碼問題
1.修改web.xml文件,在<web-app>標(biāo)簽后增加如下內(nèi)容.
<filter>
<filter-name>Set Character Encoding</filter-name>
<filter-class>com.company.demo.util.SetEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>gb2312</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Set Character Encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
2.創(chuàng)建類文件(SetEncodingFilter.java)
package com.company.demo.util;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.UnavailableException;
/**
* Set All HttpRequest Encoding
*/
public class SetEncodingFilter
implements Filter {
/**
* The default character encoding to set for requests that pass through
* this filter.
*/
protected String encoding = null;
/**
* The filter configuration object we are associated with. If this value
* is null, this filter instance is not currently configured.
*/
protected FilterConfig filterConfig = null;
/**
* Should a character encoding specified by the client be ignored?
*/
protected boolean ignore = true;
/**
* Take this filter out of service.
*/
public void destroy() {
this.encoding = null;
this.filterConfig = null;
}
/**
* Select and set (if specified) the character encoding to be used to
* interpret request parameters for this request.
*
* @param request The servlet request we are processing
* @param result The servlet response we are creating
* @param chain The filter chain we are processing
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet error occurs
*/
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (ignore || (request.getCharacterEncoding() == null)) {
request.setCharacterEncoding(selectEncoding(request));
}
chain.doFilter(request, response);
}
/**
* Place this filter into service.
* @param filterConfig The filter configuration object
*/
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
this.encoding = filterConfig.getInitParameter("encoding");
String value = filterConfig.getInitParameter("ignore");
if (value == null)
this.ignore = true;
else if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("yes"))
this.ignore = true;
else
this.ignore = false;
}
/**
* Select an appropriate character encoding to be used, based on the
* characteristics of the current request and/or filter initialization
* parameters. If no character encoding should be set, return
* <code>null</code>.
* <p>
* The default implementation unconditionally returns the value configured
* by the <strong>encoding</strong> initialization parameter for this
* filter.
*
* @param request The servlet request we are processing
*/
protected String selectEncoding(ServletRequest request) {
return (this.encoding);
}
/**
* Returns the filterConfig.
* @return FilterConfig
*/
public FilterConfig getFilterConfig() {
return filterConfig;
}
/**
* Sets the filterConfig.
* @param filterConfig The filterConfig to set
*/
public void setFilterConfig(FilterConfig filterConfig) {
this.filterConfig = filterConfig;
}
}
聯(lián)系客服