首先,在server.xml配置文件中按如下方式配置:
<Context docBase="shopping" path="/shopping" reloadable="true" source="org.eclipse.jst.j2ee.server:shopping">
<Resource name="jdbc/mysql" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="root" password="198744" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/mydb?autoReconnect=true"/>
</Context>
然后在工程的web.xml中添加如下注册代码:
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/mysql</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
调试程序通过:
<%@ page contentType="text/html;charset=gb2312" language="java" %>
<%@ page import="javax.naming.InitialContext" %>
<%@ page import="javax.sql.DataSource" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="java.sql.ResultSet" %>
<html>
<head>
<title>result.jsp</title>
</head>
<body>
<%
try{
InitialContext ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/mysql");
Connection con = ds.getConnection();
Statement smt = con.createStatement();
ResultSet rs = smt.executeQuery("select user_id, user_password, user_name, sex, birth, description from user order by birth asc");
while(rs.next()){
%>
<%=rs.getString("user_id") %>
<%=rs.getString("user_password") %>
<%=new String(rs.getString("user_name").getBytes("iso-8859-1")) %>
<%=rs.getString("sex") %>
<%=rs.getLong("birth") %>
<%=rs.getString("description") %>
<br>
<%
}
}catch(Exception e){
e.printStackTrace();
}
%>
<hr>
<a href="jstl_exec.jsp">jstl_exec.jsp</a>
<br>
username:<%=request.getParameter("username") %>
password:<%=request.getParameter("password")%>
</body>
</html>