Wednesday, September 27, 2006

Access to JavaBean as JNDI resource from JSP in TomCat 5.5

The target of an article is to build sample web application using filter servlet to obtain access to JavaBean as JNDI resource

In general we follow ch. 25.3 from [1].However,instead of creating
new bean for every new session, we create shared bean analyzing
value of object bean with call:-

bean = (MyBean) hSession.getAttribute("key");

In case when ( been == null) following code runs :-

bean = (MyBean) env.lookup("bean/MyBeanFactory");
hSession. setAttribute ("key", bean) ;

Object bean is supposed to be assigned the pointer to newly
created instance of MyBean class due to calling method
getObjectInstance( ) from MyBeanFactory class.
To get it working in TomCat 5.5.17 tune ./META-INF/context.xml to configure Tomcat's resource factory.
Web Application file layout :

Create file ./META-INF/context.xml

<Context debug="0"
docBase="JNDIBean" path="/JNDIBean" reloadable="true">
<Resource name="bean/MyBeanFactory" auth="Container"
factory="coreservlets.MyBeanFactory" />

File ./WEB-INF/web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns=""

Object factory for MyBean instances.




File JndiJsp.jsp

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<head><title>Jndi Bean</title></head> <body>
<h4>Getting Names object via JNDI ... </h4>

<jsp:useBean id="MBN" type="coreservlets.MyBean" scope="session" />
<table border = "1">
<th>Fisrt Name</th><th>Last Name</th>
<td><jsp:getProperty name="MBN" property="firstName" /></td>
<td><jsp:getProperty name="MBN" property="lastName" /></td>


package coreservlets;

public class MyBean {
private String firstName = "Missing first name";
private String lastName = "Missing last name";

public MyBean() {}

public String getFirstName() {
public void setFirstName(String firstName) {
this.firstName = firstName;
public String getLastName() {
public void setLastName(String lastName) {
this.lastName = lastName;

Modified version of

package coreservlets;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.*;
import javax.servlet.http.*;

public class JndiTFilter implements Filter {

private FilterConfig config;
private Context envCtx;

public JndiTFilter( ) { }

public void init(FilterConfig filterConfig) throws ServletException {
this.config = filterConfig;

try {
envCtx = (Context) new InitialContext().lookup("java:comp/env");
} catch (NamingException ne) {
try { envCtx.close(); } catch (NamingException nex) { }
throw new ServletException(ne);


public void doFilter(ServletRequest request,ServletResponse response, FilterChain chain)
throws IOException,ServletException {
MyBean bean = null;

HttpServletRequest hRequest = null;

if (request instanceof HttpServletRequest)
hRequest = (HttpServletRequest) request;

HttpSession hSession = hRequest.getSession();

if (hSession != null) {

// Creating shared bean with envCtx.lookup()
// Compare with source ( ch.25.3 from [1])

bean = (MyBean) hSession.getAttribute("MBN");
if (bean == null) {
try {
bean = (MyBean) envCtx.lookup("bean/MyBeanFactory");
} catch (NamingException ne) { }
hSession. setAttribute ("MBN", bean) ;

String firstName = request.getParameter("firstName");
if ((firstName != null) && (!firstName.trim().equals(""))) {
String lastName = request.getParameter("lastName");
if ((lastName != null) && (!lastName.trim().equals(""))) {
public void destroy() { }


package coreservlets;

import java.util.Enumeration;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NamingException;
import javax.naming.RefAddr;
import javax.naming.Reference;
import javax.naming.spi.ObjectFactory;

public class MyBeanFactory implements ObjectFactory {
public Object getObjectInstance(Object obj,
Name name, Context nameCtx, Hashtable environment)
throws NamingException {

// Acquire an instance of our specified bean class
MyBean bean = new MyBean();
// Customize the bean properties from our attributes

Reference ref = (Reference) obj;
Enumeration addrs = ref.getAll();
while (addrs.hasMoreElements()) {
RefAddr addr = (RefAddr) addrs.nextElement();
String nameUser = addr.getType();
String value = (String) addr.getContent();
if (nameUser.equals("firstName")) {
} else if (nameUser.equals("lastName")) {
// Return the customized instance
return (bean);


1.Java Servlet and JSP Cookbook. Bruce W. Perry. O'Reilly,2004