Spring and Hibernate with BlazeDS

mikel阅读(740)

Problem Summary
You want to use Spring and Hibernate with BlazeDS.
Solution Summary
This cookbook entry describes how you can update the store/inventory management example from Christophe Coenraets article Using BlazeDS with Spring with orM data access with Hibernate.
Explanation
Introduction
In his article Using BlazeDS with Spring Christophe Coenraets describes how you can build internet applications with a Flex front-end and a Spring back-end. The article contains a store/inventory management example with database connectivity using the Spring JDBC abstraction framework. This cookbook entry describes how you can update the store/inventory management example with orM data access with Hibernate. Hibernate is one of the most popular persistency frameworks. Since this entry extends the store/inventory management example, it assumes you successfully completed Example 2: Store/inventory management using Flex Remoting.
Step 1: Add the Hibernate libraries
First download Hibernate from http://www.hibernate.org and add the following libraries to /blazeds/tomcat/webapps/blazeds/WEB-INF/lib:

antlr.jar
cglib.jar
asm.jar
asm-attrs.jars
commons-collections.jar
commons-logging.jar
hibernate3.jar
jta.jar
dom4j.jar
log4j.jar

Step 2: Create the mapping file
Since Hibernate needs to know how to load and store objects of the Product class, we need a mapping file to tell Hibernate what table and properties to use. Create a file Product.hbm.xml in /flex-spring/samples/store/java and add the following mapping:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD
3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"
&#91;&#93;>
<hibernate-mapping package="flex.samples.spring.store">
<class name="Product" table="PRODUCT">
<id name="productId" type="long" column="PRODUCT_ID" unsaved-value="0">
<generator class="identity"/>
</id>
<property name="name" column="NAME" length="40"/>
<property name="category" column="CATEGORY" length="40"/>
<property name="image" column="IMAGE" length="40"/>
<property name="price" column="PRICE" type="double"/>
<property name="description" column="DESCRIPTION" length="255"/>
<property name="qtyInStock" column="QTY_IN_STOCK" type="integer"/>
</class>
</hibernate-mapping>

Step 3: Create the Hibernate ProductDAO implementation
Now that Hibernate knows how to store our objects, we can implement the ProductDAO interface to use Hibernate persistency. Create a new class HibernateProductDAO in the /flex-spring/samples/store/java directory and add the following lines:

package flex.samples.spring.store;
import java.util.Collection;
import o&#114;g.hibernate.HibernateException;
import o&#114;g.hibernate.Session;
import o&#114;g.hibernate.SessionFactory;
import o&#114;g.springframework.orm.hibernate3.SessionFactoryUtils;
public class HibernateProductDAO implements ProductDAO {
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public SessionFactory getSessionFactory() {
return this.sessionFactory;
}
public void cr&#101;ateProduct(Product product) {
Session session = SessionFactoryUtils.getSession(getSessionFactory(),
false);
try {
session.save(product);
} catch (HibernateException e) {
throw SessionFactoryUtils.convertHibernateAccessException(e);
}
}
public void del&#101;teProduct(Product product) {
Session session = SessionFactoryUtils.getSession(getSessionFactory(),
false);
try {
session.del&#101;te(product);
} catch (HibernateException e) {
throw SessionFactoryUtils.convertHibernateAccessException(e);
}
}
public Collection findAll() {
Session session = SessionFactoryUtils.getSession(getSessionFactory(),
false);
try {
return session.cr&#101;ateQuery("from Product").list();
} catch (HibernateException e) {
throw SessionFactoryUtils.convertHibernateAccessException(e);
}
}
public void up&#100;ateProduct(Product product) {
Session session = SessionFactoryUtils.getSession(getSessionFactory(),
false);
try {
session.up&#100;ate(product);
} catch (HibernateException e) {
throw SessionFactoryUtils.convertHibernateAccessException(e);
}
}
}

Step 4: Register the Spring beans
We need to register the new productDAOBean and a Hibernate sessionFactory in the Spring configuration. Transaction supported is added using the HibernateTransactionManager. Register the beans in the applicationContext.xml as follows:

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="mappingResources">
<list>
<value>flex/samples/spring/store/Product.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
</props>
</property>
<property name="dataSource"><ref bean="dataSource"/></property>
</bean>
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref local="sessionFactory"/>
</property>
</bean>
<bean id="productDAOBeanTarget" class="flex.samples.spring.store.HibernateProductDAO">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="productDAOBean" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager" ref="txManager" />
<property name="target" ref="productDAOBeanTarget" />
<property name="transactionAttributes">
<props>
<prop key="cr&#101;ate*">PROPAGATION_REQUIRED</prop>
<prop key="up&#100;ate*">PROPAGATION_REQUIRED</prop>
<prop key="del&#101;te*">PROPAGATION_REQUIRED</prop>
<prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>

Remove the original productDAOBean configuration.
Step 5: Update the build file
Navigate to /flex-spring/samples/store and open the file build.xml. Update the compile-java target to include the Hibernate library and to copy the mapping file:

<target name="compile-java">
<javac srcdir="java" destdir="${DEPLOY_DIR}/WEB-INF/classes"
classpath="${DEPLOY_DIR}/WEB-INF/lib/spring.jar;${DEPLOY_DIR}/WEB-INF/lib/hibernate3.jar"/>
<copy todir="${DEPLOY_DIR}/WEB-INF/classes/flex/samples/spring/store">
<fileset dir="java" includes="**/*hbm.xml"/>
</copy>
</target>

Step 6: Build the project
* Navigate to /flex-spring/samples/store.
* Execute the following command to compile and deploy the client-side and the server side of the application: ant
Step 7: Run the client application
* Restart Tomcat
* Open a browser, access http://localhost:8400/blazeds/storeadmin/index.html, and test the storeadmin application.
* Open a browser, access http://localhost:8400/blazeds/store/index.html, and test the store application.

[转]javascript 操作cookies 存(设置)、读取、删除函数实例详解

mikel阅读(627)

以前一般没想过要在JavaScript里进行COOKIES操作,不过今天碰到了,所以也发一下,作为收藏吧,以下是将这几个功能分别写成了函数.方便使用

<SCRIPT LANGUAGE="JavaScript">
//写cookies函数
function SetCookie(name,value)//两个参数,一个是cookie的名子,一个是值
{
var Days = 30; //此 cookie 将被保存 30 天
var exp  = new Date();    //new Date("December 31, 9998");
exp.setTime(exp.getTime() + Days*24*60*60*1000);
document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}
function getCookie(name)//读取cookies函数
{
var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
if(arr != null) return unescape(arr[2]); return null;
}
function delCookie(name)//删除cookie
{
var exp = new Date();
exp.setTime(exp.getTime() - 1);
var cval=getCookie(name);
if(cval!=null) document.cookie= name + "="+cval+";expires="+exp.toGMTString();
}

//简单例子

//SetCookie ("name", www.buslfy.cn)
//alert(getCookie(name));
</script>
<SCRIPT LANGUAGE="JavaScript">
function  GetCookieVal(offset)
//获得Cookie解码后的值
{
var  endstr  =  documents.cookie.indexOf  (";",  offset);
if  (endstr  ==  -1)
endstr  =  documents.cookie.length;
return  unescape(documents.cookie.substring(offset,  endstr));
}

如果点了确定,只要不清cookie,以后访问都不会再提示,如果不点确定则每次都会提示。放在js文件里,全站包含

<!--
var the_cookie = document.cookie;
var broken_cookie = the_cookie.split(":");
var the_visiteraccepted = unescape(broken_cookie&#91;1&#93;);
//
if (the_visiteraccepted=="undefined"){
var tmp=confirm(&#39;中国人何时何地。&#39;);
if(tmp==false){
window.close();
}else{
var the_visiteraccepted = 1;
var the_cookie = "ILoveChina=visiteraccepted:" + escape(the_visiteraccepted);
document.cookie = the_cookie;
}
}
//-->
</SCRIPT>

1. Cookie的兼容性问题
Cookie 的格式有2个不同的版本,第一个版本,我们称为Cookie Version 0,是最初由Netscape公司制定的,也被几乎所有的浏览器支持。而较新的版本,Cookie Version 1,则是根据RFC 2109文档制定的。为了确保兼容性,JAVA规定,前面所提到的涉及Cookie的操作都是针对旧版本的Cookie进行的。而新版本的Cookie目前还不被Javax.servlet.http.Cookie包所支持。
2. Cookie的内容
同样的 Cookie的内容的字符限制针对不同的Cookie版本也有不同。在Cookie Version 0中,某些特殊的字符,例如:空格,方括号,圆括号,等于号(=),逗号,双引号,斜杠,问号,@符号,冒号,分号都不能作为Cookie的内容。这也就是为什么我们在例子中设定Cookie的内容为”Test_Content”的原因。
虽然在Cookie Version 1规定中放宽了限制,可以使用这些字符,但是考虑到新版本的Cookie规范目前仍然没有为所有的浏览器所支持,因而为保险起见,我们应该在Cookie的内容中尽量避免使用这些字符

读取cookie的正则表达式

mikel阅读(972)

表达式

\w+=[^;]*

示例

ohkoo=Password=mikel&User=mikel; ASPSESSIONIDCCATCBCA=PLALKMLBOAJPBDCDEEHHJJNJ; ASPSESSIONIDQADCTCCC=EPNHNPMBIOFIOCCKHDABBJCL

[转]js操作cookie

mikel阅读(840)

初学ajax,昨天做项目的同时,写了一个操作cookies的js框架,比较符合jsp或者asp操作cookies的习惯(因为JavaScript里本身没有这样的对象,操作cookies等于操作字符串,所以比较麻烦)。源代码已经上传点击下载该文件,以下是框架接口说明:
对象:document.xCookie / xCookie (两个对象同等)
方法:
document.xCookie.load(d) 预加载当前已存cookies,参数d为文档对象,默认为当前文档,即document。此函数是预加载,需在所有cookie操作前使用。
document.xCookie.save() 保存对cookies的修改
document.xCookie.clear() 清除当前文档所有cookies
document.xCookie.$(name) 返回以name命名的cookie对象(document.xCookie.cookie类),相当于asp里的 Response.Cookies(name)。用点语法或[]语法访问该cookie的属性值,即 document.xCookie.$(name).prop或document.xCookie.$(name)[prop]。如果属性值不存在,则返回undefined(null)
类:document.xCookie.cookie (操作以name命名的cookie对象,document.xCookie.$(name)返回的就是这个类的实例,所以这个类的实例可以不必单独自行创建)
构造函数:
function(document, name, timeout, path, domain, secure),document为文档对象(必填);name为cookie的名字(必填);timeout为cookie过时设置,单位为分钟,可缺省,默认为暂时保存;后三个参数不在赘述,不明白的请参考有关JavaScript里的cookie知识,可缺省。
方法:
class.read(),读取当前cookie的属性值对(创建类实例时已经执行)
class.write(),写入对当前cookie的修改
class.remove(),删除当前cookie
class.toString(),返回属性值对的字符串表示形式
属性:
class.prop,访问当前cookie的prop属性
举例:
document.xCookie.load();
document.xCookie.$('myname').first='terry';
document.xCookie.$('myname').last='king';
document.xCookie.$('sex').sex='male';
document.xCookie.save();
alert(document.xCookie.$('myname').toString());
alert(document.xCookie.$('sex').toString());
备注,压缩包里一共有两个源文件,xCookie+prototype.js是沿用了prototype(1.4)框架的一些方法,需要prototype框架的支持
另外一个xCookie是没有沿用prototype框架的。
下载文件 点击下载此文件

Post还是Get

mikel阅读(845)

客户端提交调用AjaxUpdater.Update(“GET”,”userValidator.asp”,display);
后,服务器端Request不到userName和Password值

/**
类名:Ajax
创建日期:2008-3-12
版本:1.0
功能说明:
处理异步提交请求,和对请求状态的处理,以及对返回内容类型的分别处理
**/
Ajax={};
//提交请求
//method:post或get方法
//url:服务器端的URL
//callbackMethod:返回响应后的处理函数
Ajax.makeRequest=function (method,url,callbackMethod)
{    //根据浏览器类型创建request对象
if (window.XMLHttpRequest)
{
this.request=new XMLHttpRequest();
}else{
this.request=new ActiveXObject("MSXML2.XMLHTTP");
}
//设置回调函数
this.request.onreadystatechange=callbackMethod;
//设置异步请求
this.request.open(method,url,true);
//发送请求
this.request.send(url);
}
//根据返回状态代码,进行不同的页面异步显示
Ajax.checkReadyState=function(_id)
{
switch(this.request.readyState)
{
case 1:
document.getElementById(_id).innerHTML="Loading....";
break;
case 2:
document.getElementById(_id).innerHTML="Loading....";
break;
case 3:
document.getElementById(_id).innerHTML="Loading....";
break;
case 4://成功返回结果
//alert(this.request.status);
AjaxUp&#100;ater.isUpdating=false;
document.getElementById(_id).innerHTML=&#39;&#39;;
return HTTP.status(this.request.status);
default:
document.getElementById(_id).innerHTML = "An unexpected error has occurred.";
}
}
//返回请求对象的响应属性类型的内容
Ajax.getResponse=function()
{    //如果是返回内容首部含有xml格式的数据,则直接返回xml文档内容
if(this.request.getResponseHeader(&#39;Content-Type&#39;).indexOf(&#39;xml&#39;)!=-1)
{
return this.request.responseXML.documentElement;
}else
{//否则返回字符格式的文本内容
//alert(this.request.responseText);
return this.request.responseText;
}
}
/**
类名:AjaxUp&#100;ater
创建日期:2008-3-12
版本:1.0
功能说明:
处理异步提交请求,和对请求状态的处理,以及对返回内容类型的分别处理
**/
AjaxUp&#100;ater={};
//初始化设置isUpdating属性为false
AjaxUp&#100;ater.initialize=function()
{
//isUpdating用于应用程序任何地方确定一个请求是否正在运行
AjaxUp&#100;ater.isUpdating=false;
}
//初始化
AjaxUp&#100;ater.initialize();
//更新请求对象方法
//method:post或get方法
//service:也就是URL或附加?名=值&名=值的字符串
//callback:是可选参数,因为有一个默认的onResponse方法进行处理
AjaxUp&#100;ater.Up&#100;ate=function (method,service,callback)
{
//如果callback为空则默认设置onResponse方法进行处理
if(callback==undefined||callback=="")
{
callback=AjaxUp&#100;ater.onResponse;
}
//调用Ajax的发送请求方法进行异步请求
Ajax.makeRequest(method,service,callback);
//设置当前运行标识为true
AjaxUp&#100;ater.isUpdating=true;
}
//默认响应方法,当请求成功也就是=200时,将正在运行状态isUpdating设置为false,防止程序状态混乱
//注意:传入的参数loading是默认页面上id为loading的div或其他元素
//因此彼此页面中含有id为loading的元素
AjaxUp&#100;ater.onResponse=function ()
{
//返回状态200
if(Ajax.checkReadyState("loading")==200)
{
AjaxUp&#100;ater.isUpdating=false;
}
}
function initialize()
{
//alert("userValidator.asp");
AjaxUp&#100;ater.Up&#100;ate("GET","userValidator.asp",display);
}
function display()
{
try{
if(Ajax.checkReadyState(&#39;loading&#39;)==&#39;OK&#39;)
{
alert("here");
info=Utilities.getElement("info");
//alert(Ajax.getResponse());
info.innerHTML=Ajax.getResponse();
}
}catch(e)
{
//alert(e);
document.write(e);
}
}
</script>
<body>
<div id="loading"></div>
<div id="info">
<form method="post">
<div>用户登陆</div>
<div>用户名:<input type="text" id="userName" name="userName"/></div>
<div>密码:<input type="text" id="password" name="password"/></div>
<div><input type="button" value="submit" onclick="initialize();" /></div>
</form>
</div>
</body>
</html>
<%
&#39;Response.Write("<div>测试</div>")
&#39;if Request("Action")="login" then
userName=Request.QueryString("userName")
password=Request.QueryString("passWord")
if Request.QueryString("userName")="" o&#114; Request.QueryString("password")="" then
Response.Write("<div>Is Empty</div>")
else
Set rs=Server.Cr&#101;ateObject("ADODB.RecordSet")
sql="sel&#101;ct * from userInfo wh&#101;re userName=&#39;"&userName&"&#39; and password=&#39;"&password&"&#39;"
&#39;response.write sql
rs.open sql,conn,2,2
if not rs.EOF then
&#39;Response.Cookies("userInfo")
Response.Write("<div id=&#39;panel&#39;><div>我的收藏</div><div>修改资料</div><div>我的好友</div></div>")
else
Response.Write("<div>登陆失败</div>")
end if
end if
&#39;end if
%>

Request的取值方法

mikel阅读(930)

一般来说还使用万能的request(“id”)比较好
Request从几个集合取数据是有顺序的,从前到后的顺序依次是 QueryString,Form,最后是ServerVariables。Request对象按照这样的顺序依次搜索这几个集合中的变量,如果有符合的就中止,后面的就不管了。
现在我们来分析下你得问题.
假设有个页面 test.asp?id=111
这里我们的页面是用GET的方法.这时用request.querystring(“id”)与request(“id”)是一样得,应该如果不指定REQUEST得集合,首先就会从Querystring搜索.
而如果我们的页面是用的是POST的方法发送数据给test.asp,那么用request.querystring(“id”)是不行的了(他只能取 GET),而要用request.from(“id”),而如果还用request(“id”)他也能取到数据,但先检测QUERYSTRING的值,显然速度就慢了.
下面是个检测的例子你可以看看:
<% If Request("submit")<>“” then
Response.Write “直接取:”& Request(“username”) & “

Response.Write “取Get:” & Request.QueryString(“username”) & “

Response.Write “取Post:” & Request.Form(“username”) & “

End if
%>



用STOMP集成Flex3.0和RabbitMQ

mikel阅读(1086)

用STOMP集成Flex3.0和RabbitMQ
作者 Moxie Zhang译者 宋玮 发布于 2008年3月16日 下午8时48分
社区
Java
主题
RIA,
消息传送
在Flex on Rails上张贴的一篇文章中,Derek Wischusen与我们分享了他使用ActionScript 3 STOMP客户端将RabbitMQ与Flex 3集成在一起的试验。
RabitMQ是一个开源的企业消息传递系统:
RabitMQ是一个完整的、高可靠的企业消息传递系统。RabbitMQ客户端类库及后台程序(broker daemon)可一起被用于创建一个AMQP网络,或者单独使用它们以便给建立起来的网络带来RabbitMQ的好处。
RabitMQ是AMQP协议的实现,该协议是消息传递中间件的一个开放标准。STOMP则是面向流文本的消息传递协议。Wischusen所尝试的是去利用RabbitMQ的STOMP适配器。
为了使读者理解该试验是如何工作的,Wischusen给我们共享了相应的资源和源代码:
o 按照其指南所示步骤,让带有STOMP适配器的RabbitMQ来运行。
o 下载Flex例子应用的项目文件。
接下来,Wischusen解释了这个Flex例子项目到底实现了什么:
该项目有两个单独的应用组成:ImageSender和ImageReceiver。该项目文件也包含了已编译的as3-stomp类库,这样你就无需单独下载它了。
ImageSender和ImageReceiver应用将通过STOMP协议使用RabbitMQ交换消息来进行通讯。为了证明来自两个应用的Flex代码是如何与STOMP客户端一起工作的,Wischusen分享了这一代码片断。
在ImageSender方面:
“stomp” />

private function init () : void
{
var ch: ConnectHeaders = new ConnectHeaders();
ch.login = “guest”;
ch.passcode = “guest”
stomp.connect(“localhost”, 61613, ch);
}

private function sendImage():void
{
var image: ByteArray = ImageSnapshot.captureImage(canvas).data;
stomp.send(destination, image);
}
在ImageReceiver方面:
“stomp” message=”handleMessages(event)” />

private var destination: String = “/queue/images”;
private function init () : void
{
var ch: ConnectHeaders = new ConnectHeaders();
ch.login = “guest”;
ch.passcode = “guest”
stomp.connect(“localhost”, 61613, ch);
stomp.subscribe( destination );
}

private function handleMessages(event : MessageEvent) : void
{
var bd: BitmapData = new BitmapData(canvas.width, canvas.height);
var loader : flash.display.Loader = new flash.display.Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onBytesLoaded);
loader.loadBytes(event.message.body);
function onBytesLoaded (event : Event) : void
{
var content : DisplayObject = LoaderInfo( event.target ).content;
bd.draw( content );
canvas.graphics.beginBitmapFill(bd);
canvas.graphics.drawRect(0,0, canvas.width, canvas.height);
canvas.graphics.endFill();
}
}
该试验示范了一个图像是如何从Flex应用端(ImageSender)被捕获的,该图像怎么被发送至RabbitMQ服务器,消息如何被发送到消息消费者应用(ImageReceiver),以及这个消息怎样触发了一个事件而从RabbitMQ服务器装载这个图像。这是面向消息的RIA应用概念的一个有趣的演示。
查看英文原文:Integrating Flex 3.0 and RabbitMQ Using STOMP

Flex测试工具RIATest发布Beta版

mikel阅读(814)

Flex测试工具RIATest发布Beta版
作者 Moxie Zhang译者 郭晓刚 发布于 2008年3月12日 上午12时40分
社区
Java
主题
RIA
RIATest是一个Flex自动化GUI测试工具,它刚刚公开发布了Beta版。InfoQ为此采访了RIATest的创造者Tigran Najaryan。
Najaryan首先谈到了创造RIATest的目的:
RIATest是一个用来对Adobe Flex 3程序进行自动化GUI测试的工具。创造RIATest的目的是为了给商业和专业开发者提供一个简单、干净的测试自动化方案,帮助他们保证产品的质量。我们在定价上非常激进,一心把测试自动化带给更多的Flex用户,而这些用户以前都负担不起其它的Flex测试自动化方案。
说到RIATest如何工作的时候,Najaryan解释说:
从技术上看,RIATest由两部分组成:Agent和IDE(或者命令行执行器)。Agent呆在浏览器一方,直接与被测程序打交道。Agent提供了组件查看器(Component Inspector),让你检查和监视被测程序的GUI组件及其属性。Agent还通过TCP连接与IDE相连。Agent与IDE在回放期间(IDE向 Agent发送指令并接收结果)以及录制期间(Agent把录下的动作通知给IDE)都经由这个TCP连接相互沟通。
测试脚本是用RIAScript语言写的。RIAScript是一个简化版的ActionScript(另有些微扩展)——因此熟悉ActionScript的开发者很容易学会编写RIATest的测试脚本。
RIATest是用什么开发的?Najaryan回答说:
RIATest从一开始就是作为Flex 3测试自动化工具来设计的,它使用了Flex的测试自动化框架。RIATest IDE是用C++和wxWidgets库写的。RIATest Agent是用Flex 3开发的。
由于现在已经可以见到不少Flex测试工具,所以InfoQ请Najaryan将RIATest与其它工具比如FlexUnit作一下比较:
RIATest作为一个自动化GUI测试工具,与单元测试等其他测试手段是相辅相成的。必须通过多种自动化测试手段才能得到最高质量的保证,自动化GUI测试和单元测试都包括在内。
谈到如何测试连通性,如HTTP请求和SOAP连接:
RIATest内建了按照指定条件自动或手动进行同步的功能,因此即使程序需要与远程数据源通信,RIATest也能完全胜任自动化测试的工作。QA工程师可以通过“'waitfor'”操作让测试脚本与被测程序的组件状态同步。
最后,Najaryan给出了一段测试脚本的例子:
RIATest Script
查看英文原文:RIATest for Flex Released Beta Product

ASP数据库连接类

mikel阅读(858)

ASP数据库连接类
本帖发表在我是网管论坛,帖子地址:http://bbs.54master.com/119846,1,1
多数人定义conn文件的时候,都是这样.但在这样我并没有说不对.(如下代码)
conn.asp
[Copy to clipboard] [ – ]
CODE:
<% dim conn dim connstr dim db db="database/data_asp.mdb" Set conn = Server.CreateObject("ADODB.Connection") connstr="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath(db) conn.Open connstr %>
其实我们可以更好的利用conn这个文件做数据初始化的操作.今天把以前写过一个连接数据库类文件拿出来与大家分享一下,让我们一起慢慢接触ASP里的类的调用.
文档目录:
[Copy to clipboard] [ – ]
CODE:
Data:数据库文件夹
Inc :系统文件夹
inc/Fel_AsenSystem.asp:数据库类文件
Conn.asp :连接数据库文件
Index.asp:首页
很简单,我们来简单看一下Fel_AsenSystem.asp文件的代码:
[Copy to clipboard] [ – ]
CODE:
<% '文 件 名:Fel_AsenSysTem.asp '文件功能:封装类库代码 '开 发 组:Dreams Creation 项目开发组 '开发模块:数据库类 '组 成 员:特蓝克斯 '作 者:特蓝克斯 '创建时间:2006-04-20 '完成时间:?-?-? %>
<% '/*******************数据库类*******************/ Class Fel_DataBase Private ConnStr Public Property Let ConnValue(ByVal Val) ConnStr = Val End Property Public Property Get ConnValue() ConnValue = ConnStr End Property Public Function OpenConnection(DbType) Dim TempConn On Error Resume Next Set TempConn = Server.CreateObject("ADODB.Connection") TempConn.Open ConnValue Set OpenConnection = TempConn Set TempConn = Nothing If Err Then Err.Clear Response.Write "

“& DbType &”连接出错,请检查数据库连接字符串!


Response.End
Else
Response.Write “

Fellow Ver1.00 连接数据库类文件
数据库连接正常!


End If
End Function
End Class
%>
定义一个数据库类Class Fel_DataBase而这里在conn文件实例化数据库类
conn.asp
[Copy to clipboard] [ – ]
CODE:
<% '文 件 名:Conn.asp '文件功能:连接数据库文件 '开 发 组:Dreams Creation 项目开发组 '开发模块:数据库类 '组 成 员:特蓝克斯 '作 者:特蓝克斯 '创建时间:2006-04-20 %>
<% Dim DbPath Dim Conn,Rs Dim Db Dim IsSqlDataBase Dim SqlUsername,SqlPassword,SqlDatabaseName,SqlLocalName Set Db = New Fel_DataBase '实例化数据库 IsSqlDataBase = 0 '主数据库类型,"1"SQL,"0"为ACCESS '====ACCESS版 数据库参数===== Const InstallDir= "/" Rem 网站安装目录,根目录用“/”,请用"/"开头及结尾:如安装在asen_conn目录下,则值为:“/asen_conn/” DbPath = InstallDir & "Data/Data.mdb" 'Access版主数据库文件的位置(请用绝对路径) '====SQL版 数据库参数===== SqlUsername ="asen" '主数据库登录用户 SqlPassword ="asen" '主数据库登录密码 SqlDatabaseName="Fellow_cms" '主数据库名 SqlLocalName="(local)" '数据库服务器,本机用“(local)” Sub OpenConn() '连接数据库函数 if IsObject(Conn) then Exit Sub if IsSqlDataBase=1 then Db.ConnValue = "Provider = Sqloledb; User ID = " & SqlUsername & "; Password = " & SqlPassword & "; Initial Catalog = " & SqlDatabaseName & "; Data Source = " & SqlLocalName & ";" else Db.ConnValue="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath(DbPath) end If Set Conn=Db.OpenConnection("主数据库") End Sub Sub CloseAllObj() On Error Resume Next Set Db = Nothing Conn.Close:Set Conn = Nothing end Sub %>
实例化对象为
[Copy to clipboard] [ – ]
CODE:
Set Db = New Fel_DataBase '实例化数据库
代码很简单,只是提供一个这样思路给大家,要尽量合理的利用conn文件,等在以后的时间里我在给大家讲一下模板及缓存的时候,在介绍详细一些.这里代码COPY过去,就可以用.不需要改什么,当然了,路径问题是一定要考虑的,自己看吧.