Tomcat通过数据源访问数据库

来源:互联网 发布:爆破手机号软件 编辑:程序博客网 时间:2024/05/18 09:31
数据源是在JDBC2.0引入的,扩展包javax.sql.DataSource接口用来描述此概念。通过这种方式建立数据库连接时只需查询在JNDI服务中的数据源,就可以获得相应连接。
这时程序中只需一个逻辑名称,而不必关心数据库库连接的具体配置(包括DB服务器的URL、用户名、密码)。这在一定程度上避免了他人通过字节码反编译获取数据库用户名密码的危险。
另外通过这种方式建立的连接,不需要程序关心连接的释放问题。数据源会自己管理要保持多少连接,多久断开等。

1、配置context节点,如果context在server.xml中配置则在其相应位置添加。这里是把context定义在单独的.xml文件中(即Context片段),并通过docBase属性重定义了应用的路径,TOMCAT_HOME\conf\[enginename]\[hostname]\onlinetest.xml如下:
<?xml version='1.0' encoding='utf-8'?>
<Context docBase="D:/onlinetest" path="/onlinetest" reloadable="true" privileged="true">
<Resource
 name="jdbc/world"
 type="javax.sql.DataSource"
 driverClassName="com.mysql.jdbc.Driver"
 username="root"
 password="159159"
 url="jdbc:mysql://localhost/world"
 maxIdle="30"
 maxWait="5000"
 maxActive="100"/>
</Context>

注:

maxActive="最大可以有100名用户连接数据源"

maxIdle="如果没有用户连接,空出30个连接等待用户连接"

maxWait="如果已连接用户5000秒内没有再次连接数据源,则放弃此连接"

以上是访问MySql的方式,其他数据库参考:http://blog.163.com/samoyed_kk/blog/static/853760092008525462373/


2、JSP代码通过JNDI访问如下:

<%@page language="java" pageEncoding="GB2312"%>

<%@page import="java.sql.*,javax.sql.*,javax.naming.*" %>
<html><body><center>Now time is: <%=new java.util.Date()%></center></body></html>

<% 
Connection conn = null;
try
{
  InitialContext ctx = new InitialContext();
  DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/world");
  conn = ds.getConnection();

}catch(Exception e){
  out.print("Driver err!");
}
PreparedStatement pstmt = conn.prepareStatement("select * from city where name like ? and countrycode = 'CHN' order by name limit 5,10");
pstmt.setString(1, "%ng%");
ResultSet rs = pstmt.executeQuery();
%>

<thead align=center><h2><center>CityList<center></h2></thead>
<table align=center border=1>
<tr>
<td>ID</td>
<td>Name</td>
<td>Country</td>
<td>Population</td>
</tr>
<%while(rs.next()){%>
  <tr>
<td><%= new String(rs.getString("ID").getBytes("ISO8859-1"),"gb2312")%></td>
<td><%= new String(rs.getString("Name").getBytes("ISO8859-1"),"gb2312")%></td>
<td><%= new String(rs.getString("Countrycode").getBytes("ISO8859-1"),"gb2312")%></td>
<td><%= new String(rs.getString("Population").getBytes("ISO8859-1"),"gb2312")%></td>
  </tr>
<%}%>


效果如下: