Dict.CN 在线词典, 英语学习, 在线翻译

都市淘沙者

荔枝FM Everyone can be host

统计

留言簿(23)

积分与排名

优秀学习网站

友情连接

阅读排行榜

评论排行榜

Struts+Hibernate模板开发笔记 (zhuan)

Struts+Hibernate模板开发笔记

一、建立数据库联结池

二、建立测试数据库

三、建立Hibernate配置

四、把数据库的表映射为类

五、模板中的包定义

六、设计模式:单例

七、设计模式:门面

八、设计模式:DAO

九、设计模式:MVC

十、自定义标签

十一、解决汉字编码问题

一、建立数据库联结池

1.把数据库驱动程序拷入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>

二、建立测试数据库

1.建立数据库用户名 demo 密码 demo

2.建立测试表

建立测试表 demo

字段说明
id char(100)      主键
name varchar2(50)    名字
image_id number(10)   图片id
system_date date    系统日期
user_date date     录入日期

建立图片索引表 image

字段说明
id char(100)            主键
title varchar2(50)         图片标题
message varchar2(2000)       图片信息
original_image_path varchar(200)  原始图片保存路径
small _image_path varchar(200)   小图片保存路径
image_id number(10)         图片id
system_date date           系统日期

id索引表 Singleton_Id

字段说明
id char(100)     主键
name varchar2(50)  索引名(需要为此字段建索引)
value number(10)   索引id

三、建立Hibernate配置

1.拷贝Oracle9i数据库驱动程序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>

四、把数据库的表映射为类

下载 hibernate-extensions 压缩包. 修改 setenv.bat文件中的环境变量.主要修改Hibernate的目录和数据库驱动程序文件名.

例如:

@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

运行ddl2hbm.bat, 设置参数如下:

[ 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

其它的用默认值,点[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   数据模型
com.company.demo.dao       DAO模型
com.company.demo.exception    异常
com.company.demo.jdo      hibernate类映射 
com.company.demo.start      启动JSP服务时加载的类
com.company.demo.tags      自定义标签类
com.company.demo.thread     线程类
com.company.demo.util      工具类
com.company.demo.web      Struts类
com.company.demo.facade     Facade调用的类

六、设计模式:单例

1.数据模型

接口(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开发模板</p>
* <p>Description: 通用开发模板</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: 优势科技</p>
* @author 段洪杰
* @version 1.0
*/

public interface DataModule {
public SessionFactory getSessionFactory();
}

数据模型 (DatamoduleImpl.java)

package com.company.demo.datamodule;

/**
* <p>Title: Struts+Hibernate开发模板</p>
* <p>Description: 通用开发模板</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: 优势科技</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.产生唯一ID的父类

接口 (SingletonIdDAO.java)

package com.company.demo.dao;
/**
* <p>Title: Struts+Hibernate开发模板</p>
* <p>Description: 通用开发模板</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: 优势科技</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;

/**
* 产生唯一的ID
*
* 数据库结构(ORACLE9i):
* 表名 SINGLETON_ID
* 字段 id(char) name varchar2(50) value number(10.0)
*
*
* <p>Title: Struts+Hibernate开发模板</p>
* <p>Description: 通用开发模板</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: 优势科技</p>
* @author 段洪杰
* @version 1.0
*
*
*/

public class SingletonIdDAOImpl implements SingletonIdDAO{

private SessionFactory sessionFactory;
private DataModule dataModule;

/**
* 设数据模型
*/

public void setDataModule(DataModule dataModule){
this.dataModule=dataModule;
this.sessionFactory=dataModule.getSessionFactory();
}

////////////////以下是业务逻辑////////////////////
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 产唯一ID的类型名称
* @return value
* @throws HibernateException
*/

protected long getValue(String name) throws HibernateException,Exception {
SingletonId singletonId=findByName(name);
return singletonId.getValue();
}
/** 设置value
* @param name 产唯一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开发模板</p>
* <p>Description: 通用开发模板</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: 优势科技</p>
* @author 段洪杰
* @version 1.0
*/

public class ImageSingletonId extends SingletonIdDAOImpl{

private static ImageSingletonId imageSingletonId = null;

/**
* 构造函数私有
*/
private ImageSingletonId(){
}
/**
* 静态工厂模式,取得ImageSingletonId实例
*/
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测试文件(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("测试..........<BR>");
out.print(imageSingletonId.getImageValue());
out.print("----------------<BR>");
}
%>

5.单例记数器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开发模板</p>
* <p>Description: 通用开发模板</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: 优势科技</p>
* @author 段洪杰
* @version 1.0
*/

public class MainPageSingletonId extends SingletonIdDAOImpl{

private static MainPageSingletonId mainPageSingletonId = null;

/**
* 构造函数私有
*/
private MainPageSingletonId(){
}
/**
* 静态工厂模式,取得MainPageSingletonId实例
*/
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.记数ID测试文件(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("测试..........<BR>");
out.print(mainPageSingletonId.getMainPageValue());
out.print("----------------<BR>");
}
%>

7.综合单例测试(略)

七、设计模式:门面

1.在JSP中调"Session Facade"类

在JSP文件中插入下列标签:

<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开发模板</p>
* <p>Description: 通用开发模板</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: 优势科技</p>
* @author 段洪杰
* @version 1.0
*/

public class SessionBean {
private DataModule dataModule;//数据模型
private Auth auth; //登录的用户信息
private Business business; //系统中的业务逻辑主线
private Line line; //保存模块中的关联状态
/**
* 构函数,初始化业务逻辑中的类(单例)
*/
public SessionBean(){
try {
dataModule=SessionBeanSingletonFactory.getDataModule();
auth=SessionBeanSingletonFactory.getAuth();
business=SessionBeanSingletonFactory.getBusiness();
line=SessionBeanSingletonFactory.getLine();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* 门面模式调用的公共应用模块
* @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开发模板</p>
* <p>Description: 通用开发模板</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: 优势科技</p>
* @author 段洪杰
* @version 1.0
*/

public class SessionBeanFactory {
/**
* 生成业务逻辑状态实例(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开发模板</p>
* <p>Description: 通用开发模板</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: 优势科技</p>
* @author 段洪杰
* @version 1.0
*/

public class SessionBeanSingletonFactory {
/**
* 生成用户认证实例(单例)
* @return AuthImpl
* @throws HibernateException
*/

private SessionBeanSingletonFactory(){}

public final static Auth getAuth() throws HibernateException{
return new AuthImpl();
}
/**
* 生成商务逻辑实例(单例)
* @return BusinessImpl
* @throws HibernateException
*/
public final static Business getBusiness() throws HibernateException{
return new BusinessImpl();
}
/**
* 生成数据模型实例(单例)
* @return DataModuleImpl
* @throws HibernateException
*/

public final static DataModule getDataModule() throws HibernateException{
return new DataModuleImpl();
}
/**
* 生成业务逻辑状态实例(单例)
* @return LineImpl
* @throws HibernateException
*/

public final static Line getLine() throws HibernateException{
return new LineImpl();
}

}

八、设计模式:DAO

使用数据访问对象(DAO)使我们可以将底层数据访问逻辑与业务逻辑分离开。我们构建了为每一个数据源提供 GRUD (创建、读取、更新、删除)操作的 DAO 类。

下面是一个数据源GRUD(创建)操作的DAO实例.

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开发模板</p>
* <p>Description: 通用开发模板</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: 优势科技</p>
* @author 段洪杰
* @version 1.0
*/

public interface DemoDAO {

/**设置数据模型**/
public void setDataModule(DataModule dataModule);
/** 建立对象 **/
public void createDemo(Demo demo) throws HibernateException,Exception;

}

2.抽象工厂(DemoDAOFactory.java)

package com.company.demo.dao;
/**
* <p>Title: Struts+Hibernate开发模板</p>
* <p>Description: 通用开发模板</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: 优势科技</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开发模板</p>
* <p>Description: 通用开发模板</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: 优势科技</p>
* @author 段洪杰
* @version 1.0
*/

public class DemoDAOImpl implements DemoDAO {

private SessionFactory sessionFactory;
private DataModule dataModule;

/**
* 设数据模型
* @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();
}

}
}

九、设计模式:MVC

1.表示层(应用了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开发测试1.0</p>
* <p>Description:项目说明 </p>
* <p>Copyright: Copyright (c) 2003-2008 </p>
* <p>Company:优势科技 </p>
* @author 段洪杰
* @version 1.0
* @time [2003年10月22日 14时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开发测试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开发测试1.0</p>
* <p>Description:项目说明 </p>
* <p>Copyright: Copyright (c) 2003-2008 </p>
* <p>Company:优势科技 </p>
* @author 段洪杰
* @version 1.0
* @time [2003年10月22日 14时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) {
}
}

应用逻辑层(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", "系统超时,请重新登录!!!");
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"));
}
}
}

十、自定义标签

1.自定义标签库(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>日期录入标签库</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; //类型和参数名

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("类型参数错误,只能选择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("程序调用标签时出错: "+ex.getMessage());
}
return SKIP_BODY;
}
public int doEndTag() throws JspException {
return EVAL_PAGE;
}
}

十一、解决汉字编码问题

1.修改web.xml文件,在<web-app>标签后增加如下内容.

<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.创建类文件(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;
}

}

作者:快刀浪子(段洪杰)

posted on 2007-03-28 14:41 都市淘沙者 阅读(626) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航: