用j2ee版本的eclipse新建一个web动态工程。
然后在web.xml里增加jndi的配置
<resource-ref>
<description>JNDI DataSource</description>
<res-ref-name>jndi/mybatis</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
然后在里打开context.xml,增加jndi的配置
<Resource name="jndi/mybatis"
auth="Container"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/db_jndi"
username="root"
password="root123"
maxActive="20"
maxIdle="10"
maxWait="10000"/>
编写测试代码:
package com.jndi;
import java.io.IOException;
import java.sql.Connection;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
public class JndiServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
@Override
public void init() throws ServletException {
try {
Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:comp/env/jndi/mybatis");
Connection conn = ds.getConnection();
System.out.println(conn.isClosed());
} catch (Exception e) {
e.printStackTrace();
}
}
}