1.将数据库驱动复制到%TOMACT%/lib目录下,以便配置文件和程序代码使用
对于MySQL数据库,jar包下载地址:http://dev.mysql.com/downloads/connector/j/
2.在MySQL中建好数据库,这里建一个名为empdb的数据库(后面配置文件中需要用到这个名字)
3.写配置文件WEB-INF/web.xml
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
jndiDemo2
index.html
index.htm
index.jsp
default.html
default.htm
default.jsp
DB
jdbc/EmployeeDB
javax.sql.DataSource
Container
4.写配置文件META-INF/context.xml,注意数据库名要一致
driverClassName="com.mysql.jdbc.Driver"
username="root"
password=""
type="javax.sql.DataSource"
url="jdbc:mysql://localhost:3306/empdb?characterEncoding=UTF-8"/>
5.写测试代码index.jsp
pageEncoding="UTF-8"%>
Insert title hereString user = "root";
String password = "";
String driverName = "com.mysql.jdbc.Driver";
String connectURL = "jdbc:mysql://localhost:3306/empdb?useUnicode=true&characterEncoding=UTF-8";
Connection conn = null;
try {
Class.forName(driverName);
conn = DriverManager.getConnection(connectURL, user, password);
out.print("传统JDBC方式连接成功");
} catch (Exception e) {
out.print("传统JDBC方式连接失败");
}
/*
Statement stmt = null;
ResultSet rs = null;
stmt = conn.createStatement();
String sql = "select * from foodorderinfo";
rs = stmt.executeQuery(sql);
StringBuffer strbf = new StringBuffer();
while (rs.next()) {
String buywhat = rs.getString("buywhat");
strbf.append(buywhat);
}
rs.close();
stmt.close();*/
%>
Context initCtx;
initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource) envCtx.lookup("jdbc/EmployeeDB");
Connection con = ds.getConnection();
if (con != null) {
out.print("JNDI方式连接成功");
} else {
out.print("JNDI方式连接失败");
}
%>
部署运行,大功告成!
与用定制的javabean配置数据源相比,这里要求开发者需要基础的数据库知识。