tomcat5.5配置数据源

tomcat5.5配置数据源比tomcat以前的版本更加简单和简洁。

在%TOMCAT_HOME%conf/catalina/localhost/下新建一个xml文件,文件中写入如下:

<Context path="/test" docBase="H:\test\test" reloadable="true" debug="0">
  <Resource name="jdbc/bn"
   auth="Container"
   type="javax.sql.DataSource"
   driverClassName="com.microsoft.jdbc.sqlserver.SQLServerDriver"//驱动程序,需要放在tomcat下common/lib中
   maxIdle="10"
   username="sa"//用户名
   password=""//密码
   url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=pubs"//连接字符串,所要连接的数据库
   maxActive="4"/>
</Context>

test.jsp测试页面

<%@ page contentType="text/html; charset=gb2312" %>
<%@ page import="javax.naming.Context" %>
<%@ page import="javax.sql.DataSource" %>
<%@ page import="javax.naming.InitialContext" %>
<%@ page import="java.sql.*" %>
<%
DataSource ds=null;
try{
    Context initCtx=new InitialContext();
    Context envCtx=(Context)initCtx.lookup("java:comp/env");
    //从context中lookup数据源
    ds=(DataSource)envCtx.lookup("jdbc/bn");
    if(ds!=null){
        out.println("已经获得dataSource<br>");
        Connection conn=ds.getConnection();//获得连接
        Statement st=conn.createStatement();
        ResultSet rs=st.executeQuery("select * from titles");
        out.println("以下是从数据库读出的数据:<br>");
        while(rs.next()){
            out.println("title="+rs.getString("title")+"<br>");
        }
    }else{
        out.println("连接失败");
    }
}catch(Exception es){
    out.println("test.jsp-->"+es);
}
%>
测试结果:

已经获得dataSource
以下是从数据库读出的数据:
title=The Busy Executive's Database Guide
title=Cooking with Computers: Surreptitious Balance Sheets
title=You Can Combat Computer Stress!
title=Straight Talk About Computers
title=Silicon Valley Gastronomic Treats
title=The Gourmet Microwave
title=The Psychology of Computer Cooking
title=But Is It User Friendly?
title=Secrets of Silicon Valley
title=Net Etiquette
title=Computer Phobic AND Non-Phobic Individuals: Behavior Variations
title=Is Anger the Enemy?
title=Life Without Fear
title=Prolonged Data Deprivation: Four Case Studies
title=Emotional Security: A New Algorithm
title=Onions, Leeks, and Garlic: Cooking Secrets of the Mediterranean
title=Fifty Years in Buckingham Palace Kitchens
title=Sushi, Anyone?

你可能感兴趣的:(sql,tomcat,jsp,jdbc,Security)