JAVA网页设计一个毗连池的例子 (一)
他们对jsp,servlet,javabean进行封装就是为了展示他们的某个思想,与java的开发并没有必然的关系,也不见得在所以情况下,别人使用起来会简单。//文件:DbConnectionDefaultPool.java的第一部分//请注重看内里说明的一处必要修正毗连参数的中央
packagecom.qingtuo.db.pool;
importjava.sql.*;
importjava.util.*;
importjava.io.*;
importjava.text.*;
importjava.util.Date;
/**
*DefaultJiveconnectionprovider.Itusestheexcellentconnectionpool
*availablefromhttp://www.javaexchange.com.Thisconnectionproviderisa
*agoodchoiceunlessyoucanuseacontainer-managedone.
*/
publicclassDbConnectionDefaultPoolextendsDbConnectionProvider{
privatestaticfinalStringNAME="DefaultConnectionPool";
privatestaticfinalStringDESCRIPTION="Thedefaultconnectionprovider"
+"thatusestheconnectionpoolfromjavaexchange.com.Itworkswith"
+"almostanydatabasesetup,iscustomizable,andoffersgoodperformance."
+"Usethisconnectionproviderunlessyouhaveyourownorcanusea"
+"containermanagedconnectionpool.";
privatestaticfinalStringAUTHOR="CoolServlets.com";
privatestaticfinalintMAJOR_VERSION=1;
privatestaticfinalintMINOR_VERSION=0;
privatestaticfinalbooleanPOOLED=true;
privateConnectionPoolconnectionPool=null;
privatePropertiesprops;
privatePropertiespropDescriptions;
privateObjectinitLock=newObject();
publicDbConnectionDefaultPool(){
//this.manager=manager;
props=newProperties();
propDescriptions=newProperties();
//Initializeallpropertyvalues
initializeProperties();
//Loadanyexistingpropertyvalues
loadProperties();
}
/**
*Returnsadatabaseconnection.
*/
publicConnectiongetConnection(){
if(connectionPool==null){
//blockuntiltheinithasbeendone
synchronized(initLock){
//ifstillnull,somethinghasgonewrong
if(connectionPool==null){
System.err.println("Warning:DbConnectionDefaultPool.getConnection()was"+
"calledwhentheinternalpoolhasnotbeeninitialized.");
returnnull;
}
}
}
returnnewConnectionWrapper(connectionPool.getConnection(),connectionPool);
}
/**
*Startsthepool.
*/
protectedvoidstart(){
//acquirelocksothatnoconnectionscanbereturned.
synchronized(initLock){
//Getproperties
Stringdriver=props.getProperty("driver");
Stringserver=props.getProperty("server");
Stringusername=props.getProperty("username");
Stringpassword=props.getProperty("password");
intminConnections=0,maxConnections=0;
doubleconnectionTimeout=0.0;
try{
minConnections=Integer.parseInt(props.getProperty("minConnections"));
maxConnections=Integer.parseInt(props.getProperty("maxConnections"));
connectionTimeout=Double.parseDouble(props.getProperty("connectionTimeout"));
}
catch(Exceptione){
System.err.println("Error:couldnotparsedefaultpoolproperties."+
"Makesurethevaluesexistandarecorrect.");
e.printStackTrace();
return;
}
StringlogPath=props.getProperty("logPath");
try{
connectionPool=newConnectionPool(driver,server,username,password,
minConnections,maxConnections,logPath,connectionTimeout);
}
catch(IOExceptionioe){
System.err.println("ErrorstartingDbConnectionDefaultPool:"+ioe);
ioe.printStackTrace();
}
}
}
/**
*Restartsthepooltotakeintoaccountanypropertychanges.
*/
protectedvoidrestart(){
//Killoffpool.
destroy();
//Reloadproperties.
loadProperties();
//Startanewpool.
start();
}
/**
*Destroystheconnectionpool.
*/
protectedvoiddestroy(){
if(connectionPool!=null){
try{
connectionPool.destroy(1);
}
catch(Exceptione){
e.printStackTrace();
}
}
//ReleasereferencetoconnectionPool
connectionPool=null;
}
/**
*Returnsthevalueofapropertyoftheconnectionprovider.
*
*@paramnamethenameoftheproperty.
*@returnsthevalueoftheproperty.
*/
publicStringgetProperty(Stringname){
return(String)props.get(name);
}
/**
*Returnsthedescriptionofapropertyoftheconnectionprovider.
*
*@paramnamethenameoftheproperty.
*@returnthedescriptionoftheproperty.
*/
publicStringgetPropertyDescription(Stringname){
return(String)propDescriptions.get(name);
}
/**
*Returnsanenumerationofthepropertynamesfortheconnectionprovider.
*/
publicEnumerationpropertyNames(){
returnprops.propertyNames();
}
/**
*Setsapropertyoftheconnectionprovider.Eachproviderhasasetnumber
*ofpropertiesthataredeterminedbytheauthor.Tryingtosetanon-
*existantpropertywillresultinanIllegalArgumentException.
*
*@paramnamethenameofthepropertytoset.
*@paramvaluethenewvaluefortheproperty.
*
*/
publicvoidsetProperty(Stringname,Stringvalue){
props.put(name,value);
saveProperties();
}
/**
*Givedefaultvaluestoallthepropertiesanddescriptions.
*/
privatevoidinitializeProperties(){
props.put("driver","");
props.put("server","");
props.put("username","");
props.put("password","");
props.put("minConnections","");
props.put("maxConnections","");
props.put("logPath","");
props.put("connectionTimeout","");
propDescriptions.put("driver","JDBCdriver.e.g.oracle.jdbc.driver.OracleDriver");
propDescriptions.put("server","JDBCconnectstring.e.g.jdbc:oracle:thin:@203.92.21.109:1526:orcl");
propDescriptions.put("username","Databaseusername.e.g.Scott");
propDescriptions.put("password","Databasepassword.e.g.Tiger");
propDescriptions.put("minConnections","Minimum#ofconnectionstostartwithinpool.Threeistherecommendedminimum");
propDescriptions.put("maxConnections","Maximum#ofconnectionsindynamicpool.Fifteenshouldgivegoodperformanceforanaverageload.");
propDescriptions.put("logPath","Absolutepathnameforlogfile.e.g.c:logsjiveDbLog.log");
propDescriptions.put("connectionTimeout","Timeindaysbetweenconnectionresets.e.g..5");
}
/**
*Loadwhateverpropertiesthatalreadyexist.
*/
privatevoidloadProperties(){
//在这里修正一些毗连参数
//in2000
/*
Stringdriver="org.gjt.mm.mysql.Driver";
Stringserver="jdbc:mysql://192.100.100.11/pcc";
Stringusername="pcc";
Stringpassword="pcc123";
StringminConnections="3";
StringmaxConnections="10";
StringlogPath="c: empqingtuoDbLog.log";
StringconnectionTimeout="0.5";
*/
//inLinux
Stringdriver="org.gjt.mm.mysql.Driver";
Stringserver="jdbc:mysql://192.100.100.1/qingtuo";
//Stringserver="jdbc:mysql://192.168.0.1/qingtuo";
Stringusername="qingtuo";
Stringpassword="qingtuo";
StringminConnections="3";
StringmaxConnections="20";
StringlogPath="c: empqingtuoDbLog.log";
//StringlogPath="/tmp/qingtuoDbLog.log";
StringconnectionTimeout="0.5";
if(driver!=null){props.setProperty("driver",driver);}
if(server!=null){props.setProperty("server",server);}
if(username!=null){props.setProperty("username",username);}
if(password!=null){props.setProperty("password",password);}
//if(database!=null){props.setProperty("database",database);}
if(minConnections!=null){props.setProperty("minConnections",minConnections);}
if(maxConnections!=null){props.setProperty("maxConnections",maxConnections);}
if(logPath!=null){props.setProperty("logPath",logPath);}
if(connectionTimeout!=null){props.setProperty("connectionTimeout",connectionTimeout);}
}
privatevoidsaveProperties(){
PropertyManager.setProperty("DbConnectionDefaultPool.driver",props.getProperty("driver"));
PropertyManager.setProperty("DbConnectionDefaultPool.server",props.getProperty("server"));
PropertyManager.setProperty("DbConnectionDefaultPool.username",props.getProperty("username"));
PropertyManager.setProperty("DbConnectionDefaultPool.password",props.getProperty("password"));
PropertyManager.setProperty("DbConnectionDefaultPool.minConnections",props.getProperty("minConnections"));
PropertyManager.setProperty("DbConnectionDefaultPool.maxConnections",props.getProperty("maxConnections"));
PropertyManager.setProperty("DbConnectionDefaultPool.logPath",props.getProperty("logPath"));
PropertyManager.setProperty("DbConnectionDefaultPool.connectionTimeout",props.getProperty("connectionTimeout"));
}
privateclassConnectionPoolimplementsRunnable{
privateThreadrunner;
privateConnection[]connPool;
privateint[]connStatus;
privatelong[]connLockTime,connCreateDate;
privateString[]connID;
privateStringdbDriver,dbServer,dbLogin,dbPassword,logFileString;
privateintcurrConnections,connLast,minConns,maxConns,maxConnMSec;
//available:settofalseondestroy,checkedbygetConnection()
privatebooleanavailable=true;
privatePrintWriterlog;
privateSQLWarningcurrSQLWarning;
privateStringpid;
/**
*CreatesanewConnectionBroker<br>
*dbDriver:JDBCdriver.e.g.oracle.jdbc.driver.OracleDriver<br>
*dbServer:JDBCconnectstring.e.g.jdbc:oracle:thin:@203.92.21.109:1526:orcl<br>
*dbLogin:Databaseloginname.e.g.Scott<br>
*dbPassword:Databasepassword.e.g.Tiger<br>
*minConns:Minimumnumberofconnectionstostartwith.<br>
*maxConns:Maximumnumberofconnectionsindynamicpool.<br>
*logFileString:Absolutepathnameforlogfile.e.g.c: empmylog.log<br>
*maxConnTime:Timeindaysbetweenconnectionresets.(Resetdoesabasiccleanup)<br>
*/
publicConnectionPool(StringdbDriver,StringdbServer,StringdbLogin,
StringdbPassword,intminConns,intmaxConns,
StringlogFileString,doublemaxConnTime)throwsIOException
{
connPool=newConnection;
connStatus=newint;
connLockTime=newlong;
connCreateDate=newlong;
connID=newString;
currConnections=minConns;
this.maxConns=maxConns;
this.dbDriver=dbDriver;
this.dbServer=dbServer;
this.dbLogin=dbLogin;
this.dbPassword=dbPassword;
this.logFileString=logFileString;
maxConnMSec=(int)(maxConnTime*86400000.0);//86400sec/day
if(maxConnMSec<30000){//Recyclenolessthan30seconds.
maxConnMSec=30000;
}
try{
log=newPrintWriter(newFileOutputStream(logFileString),true);
//Cantopentherequestedfile.Openthedefaultfile.
}
catch(IOExceptione1){
System.err.println("Warning:DbConnectionDefaultPoolcouldnotopen""
+logFileString+""towritelogto.MakesurethatyourJava"+
"processhaspermissiontowritetothefileandthatthedirectoryexists."
);
try{
log=newPrintWriter(newFileOutputStream("DCB_"+
System.currentTimeMillis()+".log"),true
);
}
catch(IOExceptione2){
thrownewIOException("Cantopenanylogfile");
}
}
//Writethepidfile(usedtocleanupdead/brokenconnection)
SimpleDateFormatformatter
=newSimpleDateFormat("yyyy.MM.ddGathh:mm:ssazzz");
java.util.Datenowc=newjava.util.Date();
pid=formatter.format(nowc);
BufferedWriterpidout=newBufferedWriter(new
FileWriter(logFileString+"pid"));
pidout.write(pid);
pidout.close();
log.println("StartingConnectionPool:");
log.println("dbDriver="+dbDriver);
log.println("dbServer="+dbServer);
log.println("dbLogin="+dbLogin);
log.println("logfile="+logFileString);
log.println("minconnections="+minConns);
log.println("maxconnections="+maxConns);
log.println("Totalrefreshinterval="+maxConnTime+"days");
log.println("-----------------------------------------");
//Initializethepoolofconnectionswiththemininumconnections:
//Problemscreatingconnectionsmaybecausedduringrebootwhenthe
//servletisstartedbeforethedatabaseisready.Handlethis
//bywaitingandtryingagain.Theloopallows5minutesfor
//dbreboot.
booleanconnectionsSucceeded=false;
intdbLoop=20;
try{
for(inti=1;i<dbLoop;i++){
try{
for(intj=0;j<currConnections;j++){
log.println("CreateConn"+j);
createConn(j);
}
connectionsSucceeded=true;
break;
}
catch(SQLExceptione){
log.println("--->Attempt("+String.valueOf(i)+
"of"+String.valueOf(dbLoop)+
")failedtocreatenewconnectionssetatstartup:");
log.println(""+e);
log.println("Willtryagainin15seconds...");
try{Thread.sleep(15000);}
catch(InterruptedExceptione1){}
}
}
if(!connectionsSucceeded){//Allattemptsatconnectingtodbexhausted
log.println("
AllattemptsatconnectingtoDatabaseexhausted");
thrownewIOException();
}
}
catch(Exceptione){
thrownewIOException();
}
//Fireupthebackgroundhousekeepingthread
runner=newThread(this);
runner.start();
}//EndConnectionPool()
//文件:DbConnectionDefaultPool.java的第二部分
/**
*Housekeepingthread.RunsinthebackgroundwithlowCPUoverhead.
*Connectionsarecheckedforwarningsandclosureandareperiodically
*restarted.
*Thisthreadisacatchallforcorrupted
*connectionsandpreventsthebuildupofopencursors.(Opencursors
*resultwhentheapplicationfailstocloseaStatement).
*Thismethodactsasfaulttoleranceforbadconnection/statementprogramming.
*/
publicvoidrun(){
booleanforever=true;
Statementstmt=null;
StringcurrCatalog=null;
while(forever){
//Makesurethelogfileistheonethisinstanceopened
//Ifnot,cleanitup!
try{
BufferedReaderin=newBufferedReader(new
FileReader(logFileString+"pid"));
Stringcurr_pid=in.readLine();
if(curr_pid.equals(pid)){
//log.println("Theymatch="+curr_pid);
}
else{
//log.println("Nomatch="+curr_pid);
log.close();
//Closeallconnectionssilently-theyaredefinitelydead.
for(inti=0;i<currConnections;i++){
try{
connPool.close();
}
catch(SQLExceptione1){}//ignore
}
//Returningfromtherun()methodkillsthethread
return;
}
in.close();
}
catch(IOExceptione1){
log.println("Cantreadthefileforpidinfo:"+
logFileString+"pid");
}
//GetanyWarningsonconnectionsandprinttoeventfile
for(inti=0;i<currConnections;i++){
try{
currSQLWarning=connPool.getWarnings();
if(currSQLWarning!=null){
log.println("Warningsonconnection"+
String.valueOf(i)+""+currSQLWarning);
connPool.clearWarnings();
}
}
catch(SQLExceptione){
log.println("CannotaccessWarnings:"+e);
}
}
for(inti=0;i<currConnections;i++){//Doforeachconnection
longage=System.currentTimeMillis()-connCreateDate;
synchronized(connStatus){
if(connStatus>0){//Inuse,catchitnexttime!
continue;
}
connStatus=2;//Takeoffline(2indicateshousekeepinglock)
}
try{//TesttheconnectionwithcreateStatementcall
if(age>maxConnMSec){//Forcearesetatthemaxconntime
thrownewSQLException();
}
stmt=connPool.createStatement();
connStatus=0;//ConnectionisO.K.
//log.println("Connectionconfirmedforconn="+
//String.valueOf(i));
//SomeDBsreturnanobjectevenifDBisshutdown
if(connPool.isClosed()){
thrownewSQLException();
}
//Connectionhasaproblem,restartit
}
catch(SQLExceptione){
try{
log.println(newDate().toString()+
"*****Recyclingconnection"+
String.valueOf(i)+":");
connPool.close();
createConn(i);
}
catch(SQLExceptione1){
log.println("Failed:"+e1);
connStatus=0;//Cantopen,tryagainnexttime
}
}
finally{
try{
if(stmt!=null){
stmt.close();
}
}
catch(SQLExceptione1){};
}
}
try{
Thread.sleep(20000);
}//Wait20secondsfornextcycle
catch(InterruptedExceptione){
//Returningfromtherunmethodsetstheinternal
//flagreferencedbyThread.isAlive()tofalse.
//Thisisrequiredbecausewedontusestop()to
//shutdownthisthread.
return;
}
}
}//Endrun
还得说上一点,就java本质而言,是面相对象的,但是你有没有发现,java也不全是,比如说基本类型,int,那他就是整型而不是对象,转换类型是还得借助包装类。 Java自面世后就非常流行,发展迅速,对C++语言形成了有力冲击。Java 技术具有卓越的通用性、高效性、平台移植性和安全性,广泛应用于个人PC、数据中心、游戏控制台 是一种使网页(Web Page)产生生动活泼画面的语言 所以现在应用最广泛又最好学的就是J2EE了。 J2EE又包括许多组件,如Jsp,Servlet,JavaBean,EJB,JDBC,JavaMail等。要学习起来可不是一两天的事。那么又该如何学习J2EE呢?当然Java语法得先看一看的,I/O包,Util包,Lang包你都熟悉了吗?然后再从JSP学起。 还好,SUN提供了Javabean可以把你的JSP中的 Java代码封装起来,便于调用也便于重用。 一直感觉JAVA很大,很杂,找不到学习方向,前两天在网上找到了这篇文章,感觉不错,给没有方向的我指了一个方向,先不管对不对,做下来再说。 接着就是EJB了,EJB就是Enterprise JavaBean, 看名字好象它是Javabean,可是它和Javabean还是有区别的。它是一个体系结构,你可以搭建更安全、更稳定的企业应用。它的大量代码已由中间件(也就是我们常听到的 Weblogic,Websphere这些J2EE服务器)完成了,所以我们要做的程序代码量很少,大部分工作都在设计和配置中间件上。 学Java必读的两个开源程序就是Jive和Pet Store.。 Jive是国外一个非常著名的BBS程序,完全开放源码。论坛的设计采用了很多先进的技术,如Cache、用户认证、Filter、XML等,而且论坛完全屏蔽了对数据库的访问,可以很轻易的在不同数据库中移植。论坛还有方便的安装和管理程序,这是我们平时编程时容易忽略的一部份(中国程序员一般只注重编程的技术含量,却完全不考虑用户的感受,这就是我们与国外软件的差距所在)。 Java 不同于一般的编译执行计算机语言和解释执行计算机语言。它首先将源代码编译成二进制字节码(bytecode),然后依赖各种不同平台上的虚拟机来解释执行字节码。从而实现了“一次编译、到处执行”的跨平台特性。 应用在电视机、电话、闹钟、烤面包机等家用电器的控制和通信。由于这些智能化家电的市场需求没有预期的高,Sun公司放弃了该项计划。随着1990年代互联网的发展 我大二,Java也只学了一年,觉得还是看thinking in java好,有能力的话看英文原版(中文版翻的不怎么好),还能提高英文文档阅读能力。 有时间再研究一下MVC结构(把Model-View-Control分离开的设计思想) 设计模式是高级程序员真正掌握面向对象核心思想的必修课。设计模式并不是一种具体"技术",它讲述的是思想,它不仅仅展示了接口或抽象类在实际案例中的灵活应用和智慧 Java是一种计算机编程语言,拥有跨平台、面向对java 是一种使网页(Web Page)产生生动活泼画面的语言 如果要向java web方向发展也要吧看看《Java web从入门到精通》学完再到《Struts2.0入门到精通》这样你差不多就把代码给学完了。有兴趣可以看一些设计模块和框架的包等等。 是一种简化的C++语言 是一种安全的语言,具有阻绝计算机病毒传输的功能 你可以去承接一些项目做了,一开始可能有些困难,可是你有技术积累,又考虑周全,接下项目来可以迅速作完,相信大家以后都会来找你的,所以Money就哗啦啦的。。。。。。 应用在电视机、电话、闹钟、烤面包机等家用电器的控制和通信。由于这些智能化家电的市场需求没有预期的高,Sun公司放弃了该项计划。随着1990年代互联网的发展 是一种使网页(Web Page)产生生动活泼画面的语言
页:
[1]
2