Idea中配置Tomcat7的JNDI

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页面:

 

posted @ 2017-02-13 21:48  随风如梦  阅读(3933)  评论(0编辑  收藏  举报