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.6. Accessing the WebLogic JNDI Resource from a Servlet

Problem

You want to access the JNDI object created and bound on WebLogic.

Solution

Use the JNDI API in the servlet to access a reference to the bound object.

Discussion

Example 25-9 is an HttpServlet that obtains a javax.mail.Session object from WebLogic's JNDI implementation. The servlet uses this object to build an email message. The servlet initiates the JNDI lookup in its init( ) method for an object bound under the name "MyEmail" (Recipe 25.4). The servlet container calls the init( ) once when the container creates the servlet instance.

Example 25-9. Servlet to obtain a javax.mail.Session object from WebLogic's JNDI implementation and build an email message

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.mail.*;
import javax.mail.internet.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class EmailJndiServlet extends HttpServlet { private Session mailSession; public void init( ) throws ServletException { Context env = null; try{ env = (Context) new InitialContext( ); mailSession = (Session) env.lookup("MyEmail"); if (mailSession == null) throw new ServletException( "MyEmail is an unknown JNDI object"); //close the InitialContext env.close( ); } catch (NamingException ne) { try{ env.close( );} catch (NamingException nex) { } throw new ServletException(ne); ...

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