是否可以列出可用的JNDI数据源?

时间:2013-09-27 08:21:51

标签: jdbc datasource jndi

是否可以列出当前应用程序的可用JNDI数据源?如果是,我该怎么做呢。

1 个答案:

答案 0 :(得分:1)

以下是在Servlet中尝试的一些示例代码:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/plain");
    PrintWriter out = response.getWriter();
    try {
        InitialContext ictx = new InitialContext();
        Context ctx = (Context) ictx.lookup("java:");
        out.println("java: = " + ctx.getClass().getName());
        printContext(out, ctx, 1);
    } catch (Exception exc) {
        throw new ServletException(exc);
    }
}

private void printContext(PrintWriter out, Context ctx, int indent) throws ServletException, IOException, NamingException {
    NamingEnumeration en = ctx.listBindings("");
    while (en.hasMore()) {
        Binding b = (Binding) en.next();
        char[] tabs = new char[indent];
        Arrays.fill(tabs, '\t');
        out.println(new String(tabs) + b.getName() + " = " + b.getClassName());
        try {
            if (b.getObject() instanceof Context) {
                printContext(out, (Context) b.getObject(), indent + 1);
            }
        } catch (Exception exc) {
            throw new ServletException(exc);
        }
    }
}

尝试一下,让我知道它是否有效