实际项目中的StrutsPlugIn插件扩展

作者:冰莲如水

本文讲述Struts应用在实际项目中的插件类开发技术。在我们的learndiaryV1.0项目中已经有了很好的应用。通过对它的讲解,我们可以了解在应用开发中这一技术的实做经验。首先说明Struts插件扩展技术的特点:

Struts框架的一大优势在于它允许开发人员根据实际需要来扩展框架,定制客户化的功能。

Struts1.1框架提供了动态插入和加载组件的功能,这种组件被称为Struts插件。Struts插件实际上就是一个Java类,它在Struts应用启动时Struts框架调用每个插件的init()方法进行初始化,在插件的初始化阶段可以完成一些初始化的操作,如建立数据库连接,和远程系统建立连接,在当前的应用范围内加入插件类自身的实例等。在应用关闭时Struts框架会调用每个插件的 destroy()方法,destroy()方法可以用来完成释放资源的任务,如关闭数据库连接,断开与远程的连接等。任何作为插件的Java类都应该实现org.apache.struts.action.PlugIn接口。PlugIn接口包括两个方法:

       public interface PlugIn {

        /**

        *当struts应用启动时,下面的方法将被调用执行

        */

        public void init(ActionServlet servlet, ApplicationConfig config)

              throws ServletException;

       /**

       *当struts应用关闭时,将调用下面的方法,以释放资源。

       */

        public void destroy();

       }

Hibernate 存取及批量更新删除

            Hibernate 存取及批量更新删除

作者:冰莲如水

Hibernate是介于JAVA应用逻辑层与数据库层之间的一类开源的ORM中间件。ORM(即Object-Relation Mapping)从字面意义上讲就是对象-关系映射,ORM模式指的是在单个组件中负责所有实体域对象的持久化。其重点就在于把实体域对象通过一定规则上的映射机制,转化为数据库中所对应的记录,即持久化。为了更好的理解持久化,我们可以回想一下,以前所用到的通过JDBC API来对实体域对象实现的持久化。例如:

    Connetion con = null;

    PreparedStatement stmt = null;

     try{

        con = getConnection();

        con.setAutoCommit(false);

        stmt = con.prepareStatement(“insert into customers (ID, NAME, AGE) values (?,?,?)”);

        stmt.setLong(1, new Long(1));

        stmt.setString(2, new String(“ping”));

        stmt.setInt(3, new Integer(20));

        stmt.execute();

       }catch(SQLException sqlex){

           con.rollback();

         }catch(Exception e){

         …… }

        finally{

           try{

              stmt.close();

              con.close();

           }catch(Exception ex){

             …….

            }

          }

        }

Eclipse开发环境Hibernate持久层数据库存取测试(6

当你看过这一段代码后,我们再回过头来讲解一下:

  File file = new File("g:\\Eclipse3.1Workspace\\LearnDiaryV1.0\\web\\WEB-INF\\src\\hibernate.cfg.xml");

  Configuration cfg = new Configuration().configure(file);

Configuration类负责管理Hibernate的配置信息,当调用new Configuration().configure()时,默认的Hibernate会在

当前的CLASSPATH中搜寻hibernate.cfg.xml并将其加载至内存中,作为后继操作的基础配置。我们也可以替换使用

hibernate.properties这个文件,但此文件在配置条目上,不及hibernate.cfg.xml丰富灵活,此处我们选用hibernate.cfg.xml

作为配置文件。在LearnDiaryV1.0\web\WEB-INF\src目录下创建这个hibernate.cfg.xml文件,当然你也可以把它放在mypackage包

下或其它你想要找到它的地方,重要的是你要把它的绝对路径放在上面所示的FILE类下:

    new File("g:\\Eclipse3.1Workspace\\LearnDiaryV1.0\\web\\WEB-INF\\src\\hibernate.cfg.xml");

请注意正确的路径书写样式,采用"\\"表示下一级路径。

调试运行你的程序,选中窗口内的ORMService,点击工具栏中的运行图标,以Java application程序运行,注意下方的

Consle控制台输入信息,显示:

  Hibernate: insert into TEMP (NAME, VALUE, DESCRIPTION, ID) values (?, ?, ?, ?)

data has true saved!

以上英文信息很粗劣,你可以添加更正为你的正确的输出信息。本例省略了log日志创建代码。

关于Hibernate的持久化组件实现细节的解释,请详见Learndiary开发方案及相关的Hibernate教程。

初你的工作顺利,成功!

                                    冰莲如水。

Eclipse开发环境Hibernate持久层数据库存取测试(5

回到我们刚才提到的ORMService类,我们将在这个类中调用Hibernate的持久化操作,将一个新的Temp类对象

存入数据库中。这一切都是由Hibernate经由我们为temp配置的映射文件,调用其session.save(temp)操作,

在后台执行的数据库插入动作,并不由我们费力的创建显示的connection链接并书写insert语名。

ORMService类的代码如下:

package com.learndiary.website.services;

import javax.servlet.ServletContext;

import net.sf.hibernate.*;

import net.sf.hibernate.cfg.Configuration;

import net.sf.hibernate.SessionFactory;

import net.sf.hibernate.Session;

import net.sf.hibernate.Transaction;

import java.sql.Connection;

import java.io.File;

public class ORMService {

ServletContext context = null;

private static SessionFactory sessionFactory =null;

//用以测试MYSQL数据库连接的方法

public void initSessionFactory(){

try{

    File file = new File("g:\\Eclipse3.1Workspace\\LearnDiaryV1.0\\web\\WEB-INF\\src\\hibernate.cfg.xml");

Configuration cfg = new Configuration().configure(file);

SessionFactory factory = cfg.buildSessionFactory();

sessionFactory = factory;

if(sessionFactory ==null){

System.out.println("sessionFactory is null!");

}

}catch(Exception ex){

ex.printStackTrace();

}

}

public boolean saveTempData(){

boolean success = false;

String name = "binglian";

String value = "coding girl";

String description ="programer";

Session session =null;

Transaction tr =null;

try{

Temp temp = new Temp(name, value, description);

if(sessionFactory !=null){

session = sessionFactory.openSession();

tr  = session.beginTransaction();

Connection con = session.connection();

if(con !=null){

session.save(temp);

session.flush();

}else{

System.out.println("the connection is null!");

}

tr.commit();

success = true;

}else{

System.out.println("the sessionFactory is null");

}

}catch(Exception eg){

try{

if(tr !=null) {tr.rollback();}

}catch(Exception eh){

eh.printStackTrace();

}

eg.printStackTrace();

System.out.println("session save failed!");

}finally{

try{

session.close();

}catch(Exception em){

em.printStackTrace();

}

}

return success;

}

   

       public static void main(String args[]){

ORMService ser = new ORMService();

ser.initSessionFactory();

boolean saved = ser.saveTempData();

System.out.println("data has " + saved + " saved!");

}        

           

Eclipse开发环境Hibernate持久层数据库存取测试(4

再为Temp.java到数据库中的temp表做映射,映射文件名为Temp.hbm.xml,请注意书写正确的映射文件名,

Temp.hbm.xml如下:

<?xml version="1.0"?>

<!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.learndiary.website.module.beans.Temp" table="TEMP" >

    <cache usage="read-write"/>

    <id name="id" type="long" column="ID">

      <generator class="increment" />

    </id>

    <property name="name" type="string" >

      <column name="NAME" length="15"/>

    </property>

    <property name="value" type="string" >

      <column name="VALUE" length="30" />

    </property>

    <property name="description" type="string" >

      <column name="DESCRIPTION"  />

    </property>

  </class>

</hibernate-mapping>

   其中:<id name="id" type="long" column="ID">

      <generator class="increment" />

    </id>

   这一段中的  <generator class="increment" />指定temp表的 id的设置,不由应用程序设置,由MYSQL数据库

   中的内置序列号增长器控制生成序列号。即数据库将根据每次插入的记录,自动为其生成序列号。我们在执行

   Hibernate的持久层操作,对新建的Temp类对象进行持久化保存时,也不要为这个新的对象设置其id 值。

Eclipse开发环境Hibernate持久层数据库存取测试(3

以上设置为开发前的预配置。下面为Eclipse开发过程中的类及文件的创建和配置。

首先创建一个新的项目。如果是新建了一个WEB Project, 可以SRC下,设置你所要的包名。此处简化为mypackage.

在这个包名下,创建一个你用以施行持久层测试的测试类,我们把它命名为:ORMService.java ,在此之前,你可

以先创建基于数据库中temp 表的Temp.java类。 Temp.java的代码如下:

/*

 * Created on 2005-7-27

 *本类用以对MYSQL数据库的测试

 *持久层组件为Hibernate

 */

package com.learndiary.website.module.beans;

import java.io.Serializable;

/**

 * @author binglian

 *本类的hbm映射文件为:Temp.hbm

 */

public class Temp implements Serializable{

private Long id;

private String name;

private String value;

private String description;

public Temp(){

}

public Temp( String Vname, String Vvalue, String Vdescription){

this.name = Vname;

this.value =Vvalue;

this.description = Vdescription;

}

/**

* @return Returns the description.

*/

public String getDescription() {

return description;

}

/**

* @param description The description to set.

*/

public void setDescription(String description) {

this.description = description;

}

/**

* @return Returns the id.

*/

public Long getId() {

return id;

}

/**

* @param id The id to set.

*/

public void setId(Long id) {

this.id = id;

}

/**

* @return Returns the name.

*/

public String getName() {

return name;

}

/**

* @param name The name to set.

*/

public void setName(String name) {

this.name = name;

}

/**

* @return Returns the value.

*/

public String getValue() {

return value;

}

/**

* @param value The value to set.

*/

public void setValue(String value) {

this.value = value;

}

}

Eclipse开发环境Hibernate持久层数据库存取测试(2

配置MYSQL驱动程序:将MYSQL驱动的jar包考贝到你所要测试的项目的lib

              目录下,并将其路径设置为系统的环境变量,即设置CLASSPATH值,包含此

              驱动程序的路径,本例中设置如下:

               CLASSPATH值 G:\Eclipse3.1Workspace\LearnDiaryV1.0\web\WEB-INF\lib

              如果你拥有一套JBuilder开发工具,打开它,测试你的MYSQL在开发环境中

              是否可以正确连接。点击JBuilder->tool->DataBase pilot,在窗口中新建

              一个到数据库learndiary的连接。设置驱动程序名和MYSQL服务器链接地址:

              driver name:com.mysql.jdbc.Driver ;    

              database url:dbc:mysql://localhost:3306/learndiary

              如果你的MYSQL数据库位于同一域中的另一台机器上,将localhost替换为

              另一台机器的地址,如192.168.1.12, 3306为默认的访问MYSQL服务的端口

              号。接下来设置user name:root,  选中extended properties复选框,点击

              properties栏,在出现的对话框内选择add new , 点击左侧的name,value,

              依次输入:password, 1234, 双击required.保存退出。在DataBase pielot

              对话框内左侧点击MYSQL的+号,出现数据库连接中的动画。稍后数据库连接

              成功,右击MYSQL连接,选择CLOSE,关闭刚才的连接。退出JBuilder.

Eclipse开发环境下Hibernate持久层数据库存取测�

日期:2005年7月29日

作者:binglian

联系方式:binglianrushui@sohu.com

          QQ:284508610

开发环境配置:Eclipse3.0.2, Hibernate2.0, MYSQL数据库。

              打开MYSQL Command Line Client(MYSQL 服务器的客户端交互程序),

              输入ROOT用户登录密码。即你在安装MYSQL服务器时,为ROOT用户设置

              的密码。显示登录成功。创建数据库,此处命名为:learndiary. 输入

              use learndiary,起用此数据库; 注意以分号结尾。创建表:temp.

              表中包括的字段为:

              id bigint, name char(15), value char(30), description text.

              将hibernate.jar, hibernate-tools.jar包考贝到你所要测试的项目的lib

              目录下。如果你想为你的测试程序加入日志追踪,将common-logging.jar

              也考入lib目录下。