O'Reilly logo

Java Servlet & JSP Cookbook by Bruce W. Perry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

25.2. Accessing the Tomcat JNDI Resource from a Servlet

Problem

You want to access a JNDI object with a servlet using Tomcat's JNDI implementation.

Solution

Use the javax.naming classes in the servlet's init( ) method to look up a JNDI object. Then use the object in a service method like doGet( ).

Discussion

A servlet can access a JavaBean as a JNDI registered resource after you have:

  1. Developed the JavaBean class and stored it in WEB-INF/classes or in a JAR in WEB-INF/lib.

  2. Changed the server configuration file and web.xml as described in Recipe 25.1, in order to bind the object to the Tomcat JNDI tree.

Example 25-4 creates a javax.naming.InitialContext in its init( ) method, then looks up a JavaBean: com.jspservletcookbook.StockPriceBean. This bean is bound to the JNDI implementation under the name "bean/pricebean." The init( ) method is called only when the servlet container creates a servlet instance, so the servlet has access to one instance of StockPriceBean.

Example 25-4. Using a Tomcat JNDI object from a servlet

package com.jspservletcookbook;    

import java.io.IOException;  
import java.io.PrintWriter;import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;  

import javax.servlet.*;
import javax.servlet.http.*;

public class BeanServlet extends HttpServlet {

    private StockPriceBean spbean;

  public void init( ) throws ServletException {
        
      Context env = null;
        
      try{
           
          env = (Context) new InitialContext( ).lookup("java:comp/env"); spbean = (StockPriceBean) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required