tomcat jndi配置例子图

用j2ee版本的eclipse新建一个web动态工程。

然后在web.xml里增加jndi的配置

<resource-ref>
        <description>JNDI DataSourcedescription>
        <res-ref-name>jndi/mybatisres-ref-name>
        <res-type>javax.sql.DataSourceres-type>
        <res-auth>Containerres-auth>
    resource-ref>

然后在tomcat jndi配置例子图_第1张图片里打开context.xml,增加jndi的配置

    "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();
        }  
    }

}

你可能感兴趣的:(jndi,tomcat,jndi)