1、進入目錄 D:\apache-tomcat-7.0.73\conf\Catalina\localhost 添加hello.xml ,內容為:
<Context path="/hello" docBase="C:\Users\wanhua.lu\IdeaProjects\HelloWorld\out\artifacts\HelloWorld_war_exploded" reloadable="true"> <Resource name="jndi/lwh" auth="Container" type="javax.sql.DataSource" username="root" password="123456" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/demo"/> </Context>
其中 hello 是虛擬路徑的名稱, C:\Users\wanhua.lu\IdeaProjects\HelloWorld\out\artifacts\HelloWorld_war_exploded 是根據Idea中的項目發布路徑來配置
2、打開Idea的Tomcat配置界面,設置Application context,和上面的xml文件名相同:
3、將mysql的數據庫驅動 mysql-connector-java-5.0.8-bin.jar 文件放到Tomcat目錄 D:\apache-tomcat-7.0.73\lib 下面。
4、編寫一個測試JSP文件:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@page import="javax.naming.*,javax.sql.*,java.sql.*"%> <html> <head> <title>JNDI數據庫連接</title> </head> <body> <% String dsname = "java:comp/env/jndi/lwh"; Context ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup(dsname); Connection conn = ds.getConnection(); %> <%=conn %> <% conn.close(); %> </body> </html>
5、在Idea中重新啟動Tomcat,訪問我們的JSP頁面: