Wednesday, August 25, 2010

关于C#小数位数

1.简单的例子

System.Globalization.NumberFormatInfo provider = new System.Globalization.NumberFormatInfo();

provider.NumberDecimalDigits =intDecLength; //要設定的小數位數

double strCashAmt=Convert.ToDouble(this.txtCashAmt.Text); //先把控件內的值轉成double



this.txtCashAmt.Text = strCashAmt.ToString("N",provider); //再利用ToString函數格式化小數位數

2.C#保留小数位N位,四舍五入 .

decimal d= decimal.Round(decimal.Parse("0.55555"),2);

3.C#保留小数位N位四舍五入

Math.Round(0.55555,2)

4,C#保留小数位N位四舍五入

double dbdata = 0.55555;

string str1 = dbdata.ToString("f2");//fN 保留N位,四舍五入

5.C#保留小数位N位四舍五入

string result = String.Format("{0:N2}", 0.55555);//2位



string result = String.Format("{0:N3}", 0.55555);//3位

6. C#保留小数位N位四舍五入

double s=0.55555;

result=s.ToString("#0.00");//点后面几个0就保留几位


C#保留小数位数,及百分号的解决方法:

1、用NumberFormatInfo类来解决:

System.Globalization.NumberFormatInfo provider = new System.Globalization.NumberFormatInfo();



provider.PercentDecimalDigits = 2;//小数点保留几位数.

provider.PercentPositivePattern = 2;//百分号出现在何处.

double result = (double)1 / 3;//一定要用double类型.

Response.Write(result.ToString("P", provider));

2、用toString方法.:

public string getRate(double hcount, double task)

{

string rValue;

string temp = "";



if (task == 0)

{

task = 1;

}



double db = (hcount / task) * 100;



if (hcount >= task)

{

rValue = "100%";

}

else

{

rValue = db.ToString("#0.#0") + "%";

}

return rValue;

}



string str1 = String.Format("{0:N1}",56789); //result: 56,789.0

string str2 = String.Format("{0:N2}",56789); //result: 56,789.00

string str3 = String.Format("{0:N3}",56789); //result: 56,789.000

string str8 = String.Format("{0:F1}",56789); //result: 56789.0

string str9 = String.Format("{0:F2}",56789); //result: 56789.00

string str11 =(56789 / 100.0).ToString("#.##"); //result: 567.89

string str12 =(56789 / 100).ToString("#.##"); //result: 567

Monday, August 16, 2010

Install solr in windows tomcat

1. download solr like apache-solr-1.4.1
2. download tomcat 5.5 or above
3. Install tomcat
4. Extract apache-solr-1.4.1 package to anywhere
5. Copy apache-solr-1.4.1\dist\apache-solr-1.4.1.war to Tomcat webapps folder, for instance: Tomcat 5.5\webapps
6. Start tomcat and get: Tomcat 5.5\webapps\apache-solr-1.4.1 directory
7. Stop tomcat, open Tomcat 5.5\webapps\solr\WEB-INF\web.xml and copy below

<env-entry>
<env-entry-name>solr/home</env-entry-name>
<env-entry-value>C:\solr</env-entry-value>
<env-entry-type>java.lang.String</env-entry-type>
</env-entry>

to replace the old.
8. Zip apache-solr-1.4.1 and rename to solr.zip
9. Delete Tomcat 5.5\webapps\apache-solr-1.4.1 directory
10. Copy apache-solr-1.4.1\example\solr folder to c:
11. restart tomcat

That's it.

Monday, August 2, 2010

SQL Server Express Connection String

1. Working with SQL Client:
1.1 NameSpace: System.Data.SqlClient;
1.2 Objects: DataSet dataSet;
SqlConnection conn;
SqlDataAdapter dbAdapter;
1.3 Connection Strings:

1.3.1 Using Windows Authentication Mode of Connectivity:
string conString = "Server=.\\SQLEXPRESS;" +
"DataBase=yourDatabase;" +
"Integrated Security=SSPI;";

1.3.2 Using SQL Server Authentication Mode of Connectivity:
string conString = "Server=.\\SQLEXPRESS;" +
"DataBase=yourDatabase;" +
"Uid=yourUserId;Pwd=yourPassword;";

2. Working with OLEDB:
2.1 NameSpace: System.Data.OleDb;
2.2 Objects: DataSet dataSet;
OleDbConnection conn;
OleDbDataAdapter dbAdapter;
2.3 Connection Strings:

2.3.1 Using Windows Authentication Mode of Connectivity:
string conString = "Provider=SQLOLEDB;" +
"Data Source=.\\SQLEXPRESS;" +
"Initial Catalog=yourDataBase;" +
"Integrated Security=SSPI;";

2.3.2 Using SQL Server Authentication Mode of Connectivity:
string conString = "Provider=SQLOLEDB;" +
"Data Source=.\\SQLEXPRESS;" +
"Initial Catalog=yourDataBase;" +
"Uid = yourUserId; Pwd = yourPassword;";

xml operation

<p>用的是一种很笨的方法,但可以帮助初学者了解访问XML节点的过程。

已知有一个XML文件(bookstore.xml)如下:

</p><table rules="none" align="center" bgcolor="#ddedfb" border="1" bordercolor="#55aaff" cellpadding="0" cellspacing="0" width="500"> <tbody> <tr> <td width="10">
</td> <td> <p><?xml version="1.0" encoding="gb2312"?>
<bookstore>
<book genre="fantasy" isbn="2-3631-4">
<title>Oberon's Legacy</title>
<author>Corets, Eva</author>
<price>5.95</price>
</book>
</bookstore>
</p> </td> </tr> </tbody> </table> <p>

1、往<bookstore>节点中插入一个<book>节点:

</p> <p> </p><table rules="none" align="center" bgcolor="#ddedfb" border="1" bordercolor="#55aaff" cellpadding="0" cellspacing="0" width="500"> <tbody> <tr> <td width="10">
</td> <td> <p> XmlDocument xmlDoc=new XmlDocument();
xmlDoc.Load("bookstore.xml");
XmlNode root=xmlDoc.SelectSingleNode("bookstore");//查找<bookstore>
XmlElement xe1=xmlDoc.CreateElement("book");//创建一个<book>节点
xe1.SetAttribute("genre","李赞红");//设置该节点genre属性
xe1.SetAttribute("ISBN","2-3631-4");//设置该节点ISBN属性

XmlElement xesub1=xmlDoc.CreateElement("title");
xesub1.InnerText="CS从入门到精通";//设置文本节点
xe1.AppendChild(xesub1);//添加到<book>节点中
XmlElement xesub2=xmlDoc.CreateElement("author");
xesub2.InnerText="候捷";
xe1.AppendChild(xesub2);
XmlElement xesub3=xmlDoc.CreateElement("price");
xesub3.InnerText="58.3";
xe1.AppendChild(xesub3);

root.AppendChild(xe1);//添加到<bookstore>节点中
xmlDoc.Save("bookstore.xml");
</p> </td> </tr> </tbody> </table> <p>
//================
结果为:

</p> <p> </p><table rules="none" align="center" bgcolor="#ddedfb" border="1" bordercolor="#55aaff" cellpadding="0" cellspacing="0" width="500"> <tbody> <tr> <td width="10">
</td> <td> <p><?xml version="1.0" encoding="gb2312"?>
<bookstore>
<book genre="fantasy" isbn="2-3631-4">
<title>Oberon's Legacy</title>
<author>Corets, Eva</author>
<price>5.95</price>
</book>
<book genre="李赞红" isbn="2-3631-4">
<title>CS从入门到精通</title>
<author>候捷</author>
<price>58.3</price>
</book>
</bookstore>
</p> </td> </tr> </tbody> </table> <p>
2、修改节点:将genre属性值为“李赞红“的节点的genre值改为“update李赞红”,将该节点的子节点<author>的文本修改为“亚胜”。

</p><table rules="none" align="center" bgcolor="#ddedfb" border="1" bordercolor="#55aaff" cellpadding="0" cellspacing="0" width="500"> <tbody> <tr> <td width="10">
</td> <td> <p> XmlNodeList nodeList=xmlDoc.SelectSingleNode("bookstore").ChildNodes;//获取bookstore节点的所有子节点
foreach(XmlNode xn in nodeList)//遍历所有子节点
{
XmlElement xe=(XmlElement)xn;//将子节点类型转换为XmlElement类型
if(xe.GetAttribute("genre")=="李赞红")//如果genre属性值为“李赞红”
{
xe.SetAttribute("genre","update李赞红");//则修改该属性为“update李赞红”

XmlNodeList nls=xe.ChildNodes;//继续获取xe子节点的所有子节点
foreach(XmlNode xn1 in nls)//遍历
{
XmlElement xe2=(XmlElement)xn1;//转换类型
if(xe2.Name=="author")//如果找到
{
xe2.InnerText="亚胜";//则修改
break;//找到退出来就可以了
}
}
break;
}
}

xmlDoc.Save("bookstore.xml");//保存。
</p> </td> </tr> </tbody> </table>

//=================

最后结果为:

<table rules="none" align="center" bgcolor="#ddedfb" border="1" bordercolor="#55aaff" cellpadding="0" cellspacing="0" width="500"> <tbody> <tr> <td width="10">
</td> <td> <p><?xml version="1.0" encoding="gb2312"?>
<bookstore>
<book genre="fantasy" isbn="2-3631-4">
<title>Oberon's Legacy</title>
<author>Corets, Eva</author>
<price>5.95</price>
</book>
<book genre="update李赞红" isbn="2-3631-4">
<title>CS从入门到精通</title>
<author>亚胜</author>
<price>58.3</price>
</book>
</bookstore>
</p> </td> </tr> </tbody> </table>

3、删除 <book genre="fantasy" isbn="2-3631-4">节点的genre属性,删除 <book genre="update李赞红" isbn="2-3631-4">节点。

<table rules="none" align="center" bgcolor="#ddedfb" border="1" bordercolor="#55aaff" cellpadding="0" cellspacing="0" width="500"> <tbody> <tr> <td width="10">
</td> <td> <p>XmlNodeList xnl=xmlDoc.SelectSingleNode("bookstore").ChildNodes;

foreach(XmlNode xn in xnl)
{
XmlElement xe=(XmlElement)xn;</p> </td> </tr> </tbody> </table>
if(xe.GetAttribute("genre")=="fantasy")
{
xe.RemoveAttribute("genre");//删除genre属性
}
else if(xe.GetAttribute("genre")=="update李赞红")
{
xe.RemoveAll();//删除该节点的全部内容
}
}
xmlDoc.Save("bookstore.xml");

//====================

最后结果为:

<table rules="none" align="center" bgcolor="#ddedfb" border="1" bordercolor="#55aaff" cellpadding="0" cellspacing="0" width="500"> <tbody> <tr> <td width="10">
</td> <td><?xml version="1.0" encoding="gb2312"?>
<bookstore>
<book isbn="2-3631-4">
<title>Oberon's Legacy</title>
<author>Corets, Eva</author>
<price>5.95</price>
</book>
<book>
</book>
</bookstore></td> </tr> </tbody> </table>

4、显示所有数据。

<table rules="none" align="center" bgcolor="#ddedfb" border="1" bordercolor="#55aaff" cellpadding="0" cellspacing="0" width="500"> <tbody> <tr> <td width="10">
</td> <td> <p> XmlNode xn=xmlDoc.SelectSingleNode("bookstore");

XmlNodeList xnl=xn.ChildNodes;

foreach(XmlNode xnf in xnl)
{
XmlElement xe=(XmlElement)xnf;
Console.WriteLine(xe.GetAttribute("genre"));//显示属性值
Console.WriteLine(xe.GetAttribute("ISBN"));

XmlNodeList xnf1=xe.ChildNodes;
foreach(XmlNode xn2 in xnf1)
{
Console.WriteLine(xn2.InnerText);//显示子节点点文本
}
} </p> </td> </tr> </tbody> </table> <p> </p> <p>
转载自:http://blog.csdn.net/s98/archive/2004/10/17/140307.aspx


XmlDocument xmlDoc=new XmlDocument();
xmlDoc.Load("c:/aaa.xml");
XmlNode xn=xmlDoc.SelectSingleNode("todate");
XmlNodeList xnl=xn.ChildNodes;
foreach(XmlNode xnf in xnl)
{
XmlElement xe=(XmlElement)xnf;

XmlNodeList xnf1=xe.ChildNodes;

Response.Write(xnf1[0].InnerText);//显示子节点点文本
} </p> <p> XmlDocument xmlDoc=new XmlDocument();
xmlDoc.Load("c:/aaa.xml");
XmlNode xn=xmlDoc.SelectSingleNode("todate");
XmlNodeList xnl=xn.ChildNodes;
foreach(XmlNode xnf in xnl)
{
XmlElement xe=(XmlElement)xnf;

XmlNodeList xnf1=xe.ChildNodes;

xnf1[0].InnerText="10";
xmlDoc.Save("c:/aaa.xml");</p>

Thursday, June 10, 2010

一些常用的正则表达式

正则表达式用于字符串处理,表单验证等场合,实用高效,但用到时总是不太把握,以致往往要上网查一番。我将一些常用的表达式收藏在这里,作备忘之用。本贴随时会更新。

匹配中文字符的正则表达式: [\u4e00-\u9fa5]

匹配双字节字符(包括汉字在内):[^\x00-\xff]

应用:计算字符串的长度(一个双字节字符长度计2,ASCII字符计1)

String.prototype.len=function(){return this.replace([^\x00-\xff]/g,”aa”).length;}

匹配空行的正则表达式:\n[\s ]*\r

匹配HTML标记的正则表达式:/<(.*)>.*<\/\1><(.*) \/>/

匹配首尾空格的正则表达式:(^\s*)(\s*$)

应用:javascript中没有像vbscript那样的trim函数,我们就可以利用这个表达式来实现,如下:

String.prototype.trim = function()
{
return this.replace(/(^\s*)(\s*$)/g, “”);
}

利用正则表达式分解和转换IP地址:

下面是利用正则表达式匹配IP地址,并将IP地址转换成对应数值的Javascript程序:

function IP2V(ip)
{
re=/(\d+)\.(\d+)\.(\d+)\.(\d+)/g //匹配IP地址的正则表达式
if(re.test(ip))
{
return RegExp.$1*Math.pow(255,3))+RegExp.$2*Math.pow(255,2))+RegExp.$3*255+RegExp.$4*1
}
else
{
throw new Error(“Not a valid IP address!”)
}
}

不过上面的程序如果不用正则表达式,而直接用split函数来分解可能更简单,程序如下:

var ip=”10.100.20.168″
ip=ip.split(“.”)
alert(“IP值是:”+(ip[0]*255*255*255+ip[1]*255*255+ip[2]*255+ip[3]*1))

匹配Email地址的正则表达式:\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*

匹配网址URL的正则表达式:http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?

利用正则表达式去除字串中重复的字符的算法程序:[注:此程序不正确,原因见本贴回复]

var s=”abacabefgeeii”
var s1=s.replace(/(.).*\1/g,”$1″)
var re=new RegExp(“["+s1+"]“,”g”)
var s2=s.replace(re,”")
alert(s1+s2) //结果为:abcefgi

我原来在CSDN上发贴寻求一个表达式来实现去除重复字符的方法,最终没有找到,这是我能想到的最简单的实现方法。思路是使用后向引用取出包括重复的字符,再以重复的字符建立第二个表达式,取到不重复的字符,两者串连。这个方法对于字符顺序有要求的字符串可能不适用。

得用正则表达式从URL地址中提取文件名的javascript程序,如下结果为page1

s=”http://www.9499.net/page1.htm”
s=s.replace(/(.*\/){0,}([^\.]+).*/ig,”$2″)
alert(s)

利用正则表达式限制网页表单里的文本框输入内容:

用正则表达式限制只能输入中文:onkeyup=”value=value.replace(/[^\u4E00-\u9FA5]/g,”)” onbeforepaste=”clipboardData.setData(‘text’,clipboardData.getData(‘text’).replace(/[^\u4E00-\u9FA5]/g,”))”

用正则表达式限制只能输入全角字符: onkeyup=”value=value.replace(/[^\uFF00-\uFFFF]/g,”)” onbeforepaste=”clipboardData.setData(‘text’,clipboardData.getData(‘text’).replace(/[^\uFF00-\uFFFF]/g,”))”

用正则表达式限制只能输入数字:onkeyup=”value=value.replace(/[^\d]/g,”) “onbeforepaste=”clipboardData.setData(‘text’,clipboardData.getData(‘text’).replace(/[^\d]/g,”))”

用正则表达式限制只能输入数字和英文:onkeyup=”value=value.replace(/[\W]/g,”) “onbeforepaste=”clipboardData.setData(‘text’,clipboardData.getData(‘text’).replace(/[^\d]/g,”))”

正则表达式,相关链接
http://blog.csdn.net/laily/category/19548.aspx
http://blog.csdn.net/laily/archive/2004/06/30/30525.aspx 微软的正则表达式教程(五):选择/编组和后向引用

http://blog.csdn.net/laily/archive/2004/06/30/30522.aspx 微软的正则表达式教程(四):限定符和定位符

http://blog.csdn.net/laily/archive/2004/06/30/30517.aspx 微软的正则表达式教程(三):字符匹配

http://blog.csdn.net/laily/archive/2004/06/30/30514.aspx 微软的正则表达式教程(二):正则表达式语法和优先权顺序

http://blog.csdn.net/laily/archive/2004/06/30/30511.aspx 微软的正则表达式教程(一):正则表达式简介

http://blog.csdn.net/laily/archive/2004/06/30/30360.aspx 小程序大作为:高级查找/替换、正则表达式练习器、Javascript脚本程序调试器

http://blog.csdn.net/laily/archive/2004/06/24/25872.aspx 经典正则表达式

正则表达式,正规表达式,正则表达式匹配,正则表达式语法,模式匹配,正规表达式匹配 javascript正则表达式 ASP正则表达式 ASP.NET正则表达式 C#正则表达式 JSP正则表达式 PHP正则表达式 VB.NET正则表达式 VBSCript正则表达式编程 delphi正则表达式 jscript

补充:
^\d+$  //匹配非负整数(正整数 + 0)
^[0-9]*[1-9][0-9]*$  //匹配正整数
^((-\d+)(0+))$  //匹配非正整数(负整数 + 0)
^-[0-9]*[1-9][0-9]*$  //匹配负整数
^-?\d+$    //匹配整数
^\d+(\.\d+)?$  //匹配非负浮点数(正浮点数 + 0)
^(([0-9]+\.[0-9]*[1-9][0-9]*)([0-9]*[1-9][0-9]*\.[0-9]+)([0-9]*[1-9][0-9]*))$  //匹配正浮点数
^((-\d+(\.\d+)?)(0+(\.0+)?))$  //匹配非正浮点数(负浮点数 + 0)
^(-(([0-9]+\.[0-9]*[1-9][0-9]*)([0-9]*[1-9][0-9]*\.[0-9]+)([0-9]*[1-9][0-9]*)))$  //匹配负浮点数
^(-?\d+)(\.\d+)?$  //匹配浮点数
^[A-Za-z]+$  //匹配由26个英文字母组成的字符串
^[A-Z]+$  //匹配由26个英文字母的大写组成的字符串
^[a-z]+$  //匹配由26个英文字母的小写组成的字符串
^[A-Za-z0-9]+$  //匹配由数字和26个英文字母组成的字符串
^\w+$  //匹配由数字、26个英文字母或者下划线组成的字符串
^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$    //匹配email地址
^[a-zA-z]+://匹配(\w+(-\w+)*)(\.(\w+(-\w+)*))*(\?\S*)?$  //匹配url
利用正则表达式去除字串中重复的字符的算法程序:

var s=”abacabefgeeii”
var s1=s.replace(/(.).*\1/g,”$1″)
var re=new RegExp(“["+s1+"]“,”g”)
var s2=s.replace(re,”")
alert(s1+s2) //结果为:abcefgi
===============================
如果var s = “abacabefggeeii”
结果就不对了,结果为:abeicfgg
正则表达式的能力有限
1.确认有效电子邮件格式
下面的代码示例使用静态 Regex.IsMatch 方法验证一个字符串是否为有效电子邮件格式。如果字符串包含一个有效的电子邮件地址,则 IsValidEmail 方法返回 true,否则返回 false,但不采取其他任何操作。您可以使用 IsValidEmail,在应用程序将地址存储在数据库中或显示在 ASP.NET 页中之前,筛选出包含无效字符的电子邮件地址。

[Visual Basic]
Function IsValidEmail(strIn As String) As Boolean
‘ Return true if strIn is in valid e-mail format.
Return Regex.IsMatch(strIn, (“^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)(([\w-]+\.)+))([a-zA-Z]{2,4}[0-9]{1,3})(\]?)$”)
End Function
[C#]
bool IsValidEmail(string strIn)
{
// Return true if strIn is in valid e-mail format.
return Regex.IsMatch(strIn, @”^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)(([\w-]+\.)+))([a-zA-Z]{2,4}[0-9]{1,3})(\]?)$”);
}

2.清理输入字符串
下面的代码示例使用静态 Regex.Replace 方法从字符串中抽出无效字符。您可以使用这里定义的 CleanInput 方法,清除掉在接受用户输入的窗体的文本字段中输入的可能有害的字符。CleanInput 在清除掉除 @、-(连字符)和 .(句点)以外的所有非字母数字字符后返回一个字符串。

[Visual Basic]
Function CleanInput(strIn As String) As String
‘ Replace invalid characters with empty strings.
Return Regex.Replace(strIn, “[^\w\.@-]“, “”)
End Function
[C#]
String CleanInput(string strIn)
{
// Replace invalid characters with empty strings.
return Regex.Replace(strIn, @”[^\w\.@-]“, “”);
}

3.更改日期格式
以下代码示例使用 Regex.Replace 方法来用 dd-mm-yy 的日期形式代替 mm/dd/yy 的日期形式。

[Visual Basic]
Function MDYToDMY(input As String) As String
Return Regex.Replace(input, _
“\b(?\d{1,2})/(?\d{1,2})/(?\d{2,4})\b”, _
“${day}-${month}-${year}”)
End Function
[C#]
String MDYToDMY(String input)
{
return Regex.Replace(input,
“\\b(?\\d{1,2})/(?\\d{1,2})/(?\\d{2,4})\\b”,
“${day}-${month}-${year}”);
}
Regex 替换模式
本示例说明如何在 Regex.Replace 的替换模式中使用命名的反向引用。其中,替换表达式 ${day} 插入由 (?…) 组捕获的子字符串。

有几种静态函数使您可以在使用正则表达式操作时无需创建显式正则表达式对象,而 Regex.Replace 函数正是其中之一。如果您不想保留编译的正则表达式,这将给您带来方便

4.提取 URL 信息
以下代码示例使用 Match.Result 来从 URL 提取协议和端口号。例如,“http://www.contoso.com:8080/letters/readme.html”将返回“http:8080”。

[Visual Basic]
Function Extension(url As String) As String
Dim r As New Regex(“^(?\w+)://[^/]+?(?:\d+)?/”, _
RegexOptions.Compiled)
Return r.Match(url).Result(“${proto}${port}”)
End Function
[C#]
String Extension(String url)
{
Regex r = new Regex(@”^(?\w+)://[^/]+?(?:\d+)?/”,
RegexOptions.Compiled);
return r.Match(url).Result(“${proto}${port}”);
}

Wednesday, January 20, 2010

disable Axis2 soapAction

Sometimes we want to disable soapAction of Axis2 to communicate .Net WCF webservice.

Add below in NetworkNode2Stub.java


//adding SOAP soap_headers
_serviceClient.addHeadersToEnvelope(env);
// set the message context with that soap envelope
_messageContext.setEnvelope(env);

// add the message contxt to the operation client
_operationClient.addMessageContext(_messageContext);

// Disable SOAP_ACTION to fix .Net endpoint without soapAction
_operationClient.getOptions().setProperty(

org.apache.axis2.Constants.Configuration.DISABLE_SOAP_ACTION,
org.apache.axis2.Constants.VALUE_TRUE);

//execute the operation client
_operationClient.execute(true);

Friday, January 8, 2010

Tomcat 5.X setup jndi

1. Copy jdbc driver to Tomcat 5.X\common\lib
2. Romove all commons-dbcp-x.x.x,commons-pool-x.x and jdbc driver from application/WEB-INF/lib

3. Add Context and jndi parameters in server.xml file as below:

Tomcat 5.0.xx:
(the entity way) was the only way that worked.

[server.xml]:
<Service...>
<Engine...>
<Host...>
...
<Context crossContext="true" docBase="/opt/tomcat5/webapps/oracleTest" path="/oracleTest" reloadable="true">
<Resource name="jdbc/myoracle" auth="Container"
type="javax.sql.DataSource"/>
<ResourceParams name="jdbc/myoracle">
<parameter>
<name>factory</name>
<value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
</parameter>
<parameter>
<name>driverClassName</name>
<value>oracle.jdbc.OracleDriver</value>
</parameter>
<parameter>
<name>url</name>
<value>jdbc:oracle:thin:@15.1.1.40:1521:dbastra</value>
</parameter>
<parameter>
<name>username</name>
<value>uuuuuu</value>
</parameter>
<parameter>
<name>password</name>
<value>xxxxxxxx</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>
<Resource name="jdbc/myoracle5" auth="Container"
type="javax.sql.DataSource" />
</Context>
</Host>
</Engine>
</Service>

Tomcat 5.5.xx:
(the attributes way) was the only way that worked.

[server.xml]:
<Service...>
<Engine...>
<Host...>
...
<Context path="/oracleTest" reloadable="true"
docBase="/opt/tomcat5/webapps/oracleTest">

<Logger className="org.apache.catalina.logger.SystemOutLogger"
verbosity="4" timestamp="true" />

<Resource name="jdbc/myoracle5" auth="Container"
type="javax.sql.DataSource" driverClassName="oracle.jdbc.OracleDriver"
url="jdbc:oracle:thin:@15.1.1.40:1521:dbastra" username="aradmin"
password="ar#admin#" maxActive="20" maxIdle="10" maxWait="-1" />

</Context>
</Host>
</Engine>
</Service>

for BOTH versions:

Here there are some points we should take a look:

<Context> in [server.xml] !!
"Please note that for tomcat 5, unlike tomcat 4.x, it is NOT recommended to place <Context> elements directly in the server.xml file. Instead, put them in the META-INF/context.xml directory of your WAR file or the conf directory as described above."
http://tomcat.apache.org/tomcat-5.5-doc/config/context.html

And if we cut the <Context>..</Context> body we described above from the server.xml and paste it into [META-INF/context.xml] or into [conf/Catalina/localhost/oracleTest.xml], it works...


<?xml version='1.0' encoding='utf-8'?>
<Context crossContext="true" docBase="/forge/oracleTest" path="/oracleTest" reloadable="true">
<Logger className="org.apache.catalina.logger.FileLogger"
prefix="localhost_DBTest_log." suffix=".txt" timestamp="true" />

<Resource ... (the one that applies to your version)>

</Context>

GlobalNamingResources:
"GlobalNamingResources element defines the global JNDI resources for the Server. These resources are listed in the server's global JNDI resource context. This context is distinct from the per-web-application JNDI contexts described in the JNDI Resources HOW-TO. The resources defined in this element are not visible in the per-web-application contexts unless you explicitly link them with <ResourceLink> elements."
http://tomcat.apache.org/tomcat-5.5-doc/config/globalresources.html
http://tomcat.apache.org/tomcat-5.5-doc/config/context.html#Resource%20Links


Article From http://forums.sun.com/thread.jspa?threadID=567630&start=15