「Tomcat」 JNDI 使ってみる

Tomcat で JNDI 使ってみたので、その時のメモ。

[ 環境情報 ]
Windows 7
Apache Tomcat 7.0.27
Java SE 7

1. JNDI に登録するプログラムを作成する。

package jndi.test;

public class Hello {
	public String hello(String name) {
		return name + "hello !!";
	}
}

2. web.xml で JNDI を登録する

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  
  <resource-env-ref>
    <description>JNDI Test</description>
  <resource-env-ref-name>jndi/test</resource-env-ref-name>
  <resource-env-ref-type>jndi.test.Hello</resource-env-ref-type>
</resource-env-ref>
</web-app>

3. context.xml にリソースファクトリの設定をする

<?xml version="1.0" encoding="UTF-8"?>
<Context>
  <Resource name="jndi/test"
            auth="Container"
            type="jndi.test.Hello"
            factory="org.apache.naming.factory.BeanFactory" />
</Context>

※ ひとまず、上記の設定で動きましたが、factory に何を設定すればいいのかってあたりはちょっとよくわからずでした・・・
ちなみに、Tomcat では以下のようなファクトリクラスが用意されてるっぽい。
・Index of /tomcat-7.0-doc/api/org/apache/naming/factory
http://tomcat.apache.org/tomcat-7.0-doc/api/org/apache/naming/factory/

4. JNDI を lookup するサーブレットを作成する

package jndi.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jndi.test.Hello;

@WebServlet("/JndiServlet")
public class JndiServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public JndiServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String s = null;
		try {
			Context initCtx = new InitialContext();
			Context envCtx = (Context) initCtx.lookup("java:comp/env");
			Hello h = (Hello) envCtx.lookup("jndi/test");
			s = h.hello("hoge");
		} catch (NamingException e) {
			e.printStackTrace();
		}

		PrintWriter out = response.getWriter();
		out.println("<html>");
		out.println("<body>");
		out.println(s);
		out.println("</body>");
		out.println("</html>");
	}
}

Tomcat では全てのリソースが "java:comp/env" に置かれるとのことです。
-----
All configured entries and resources are placed in the java:comp/env portion of the JNDI namespace ・・・
-----



上記が終わったら、適当に war ファイルにして Tomcat 上にデプロイ。
そして、http://localhost:8080/jndiTest/JndiServlet にアクセスして「hoge hello !!」と出力されれば成功。


ドキュメントは以下になりますね。
Apache Tomcat 7 (7.0.42) - JNDI Resources HOW-TO
http://tomcat.apache.org/tomcat-7.0-doc/jndi-resources-howto.html

以上です。