EJB.RUH
Reuse EJB homes
Description
This rule flags code that does not reuse EJB homes but should. This rule only applies to simple applications.
EJB homes are obtained from the WebSphere Application Server through a JNDI naming lookup. This is an expensive operation that can be minimized by caching and reusing EJB Home objects.
Example
package EJB;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.rmi.*;
import javax.naming.*;
public class RUH extends HttpServlet {
public void transaction () throws ServletException {
Context ctx = null;
try {
ctx = new InitialContext (new java.util.Hashtable ());
Object homeObject = ctx.lookup ("EJB JNDI NAME");
//violation, Home interface should not be a local
// variable.
AccountHome aHome = (AccountHome)Portable
RemoteObject.narrow (
homeObject, AccountHome.class);
} catch (Exception e) {
throw new ServletException ("INIT ERROR" +e.getMessage
(), e);
} finally {
try {
if (ctx != null) ctx.close ();
} catch (Exception e) {}
}
}
}
Repair
Cache EJB Home in Servlet init method.
import javax.servlet.*;
import javax.servlet.http.*;
import javax.naming.*;
public class rw137_correct extends HttpServlet {
private AccountHome aHome = null; // cache Home interface.
public void init (ServletConfig config) throws ServletException
{
super.init (config);
Context ctx = null;
try {
ctx = new InitialContext (new java.util.Hashtable ());
Object homeObject = ctx.lookup ("EJB JNDI NAME");
aHome = (AccountHome)javax.rmi.PortableRemoteObject.nar-
row (
homeObject, AccountHome.class);
} catch (Exception e) {
throw new ServletException ("INIT ERROR" +e.getMessage
(), e);
} finally {
try {
if (ctx != null) ctx.close ();
} catch (Exception e) {}
}
}
}
For simple applications, it might be enough to acquire the EJB home in the servlet init() method.
More complicated applications might require cached EJB homes in many servlet and EJBs. In these cases, you might want to create an EJB Home Locator and Caching class.
Reference
IBM WebSphere Application Server Standard and Advanced Editions, Harvey W. Gunther.
http://www-4.ibm.com/software/webservers/appserv/ws_bestpractices.pdf
|