1.将数据库驱动复制到%TOMACT%/lib目录下,以便配置文件和程序代码使用
对于MySQL数据库,jar包下载地址:http://dev.mysql.com/downloads/connector/j/
2.在MySQL中建好数据库,这里建一个名为empdb的数据库(后面配置文件中需要用到这个名字)
3.写配置文件WEB-INF/web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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">
<display-name>jndiDemo2</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<resource-ref>
<description>DB</description>
<res-ref-name>jdbc/EmployeeDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
4.写配置文件META-INF/context.xml,注意数据库名要一致
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="jdbc/EmployeeDB" auth="Container"
driverClassName="com.mysql.jdbc.Driver"
username="root"
password=""
type="javax.sql.DataSource"
url="jdbc:mysql://localhost:3306/empdb?characterEncoding=UTF-8"/>
</Context>
5.写测试代码index.jsp
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@page import="javax.sql.DataSource"%>
<%@ page import="javax.naming.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String 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();*/
%>
<br />
<%
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方式连接失败");
}
%>
</body>
</html>
部署运行,大功告成!
与用定制的javabean配置数据源相比,这里要求开发者需要基础的数据库知识。