(1)配置context.xml文件(Tomcat/conf目录下或在WEB项目中META-INF目录下创建一个context.xml文件)
<Context>
<Resource
name="jdbc/news"
auth="Container"
type="javax.sql.DataSource"
maxActive="100"
maxIDlle="20"
maxWait="10000"
username="root"
password="123456"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://127.0.0.1:3306/conmy?useUnicode=true&characterEncoding=utf-8"/>
</Context>
(2)配置web.xml文件(在WEB项目中WEB-IN目录下)
<web-app>
<resource-ref>
<description>news DataSource</description>
<res-ref-name>jdbc/news</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
(3)添加驱动,驱动放在tomcat文件夹内lib目录下
(4)编写代码连接代码(不可以直接写在main方法下)
public class BaseDao {
public Connection getConnection() {
Connection conn=null;
try {
Context cxt=new InitialContext();
DataSource ds=(DataSource)cxt.lookup("java:comp/env/jdbc/news");
conn=ds.getConnection();
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
}
(5)在jsp页面调用数据连接(Connection)对象
<%
BaseDao bd=new BaseDao();
Connection conn=bd.getConnection();
%>
<%=conn %>