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"
type="coreservlets.MyBean"
factory="coreservlets.MyBeanFactory" />
</Context>
*************************
File ./WEB-INF/web.xml
*************************
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<resource-env-ref>
<description>
Object factory for MyBean instances.
</description>
<resource-env-ref-name>
bean/MyBeanFactory
</resource-env-ref-name>
<resource-env-ref-type>
coreservlets.MyBean
</resource-env-ref-type>
</resource-env-ref>
<filter>
<filter-name>JndiFilter</filter-name>
<filter-class>coreservlets.JndiTFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>JndiFilter</filter-name>
<url-pattern>/JndiJsp.jsp</url-pattern>
</filter-mapping>
</web-app>
****************
File JndiJsp.jsp
****************
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<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">
<tr>
<th>Fisrt Name</th><th>Last Name</th>
</tr>
<tr>
<td><jsp:getProperty name="MBN" property="firstName" /></td>
<td><jsp:getProperty name="MBN" property="lastName" /></td>
</tr>
</table>
</body>
</html>
*****************
File MyBean.java
*****************
package coreservlets;
public class MyBean {
private String firstName = "Missing first name";
private String lastName = "Missing last name";
public MyBean() {}
public String getFirstName() {
return(firstName);
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return(lastName);
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
*************************************
Modified version of JndiTFilter.java
*************************************
package coreservlets;
import java.io.IOException;
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");
envCtx.close();
} 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(""))) {
bean.setFirstName(firstName);
}
String lastName = request.getParameter("lastName");
if ((lastName != null) && (!lastName.trim().equals(""))) {
bean.setLastName(lastName);
}
}
chain.doFilter(request,response);
}
public void destroy() { }
}
**************************
File MyBeanFactory.java
**************************
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")) {
bean.setFirstName(value);
} else if (nameUser.equals("lastName")) {
bean.setLastName(value);
}
}
// Return the customized instance
return (bean);
}
}
References.
1.Java Servlet and JSP Cookbook. Bruce W. Perry. O'Reilly,2004