Christopher Cobb wrote:
>
> How do you specify an entity that you want to be global across applications?
>
The standard Java approach of using a class with public static methods is the usual
technique for accomplishing this. This is often referred to as the "singleton"
pattern. An example of this approach is the DateFormat.getDateInstance() method, which
returns you a DateFormat object. Because this is a static method, you can call it from
anywhere (including from any servlet-based application).
However, you must be aware of class loader issues to ensure that this works the way you
intended. If everything in the servlet container is loaded by a single ClassLoader
instance (as is the case with JSWDK and the current version of Jakarta Tomcat, but
*not*
the case for many existing servlet engines), the standard approach works fine.
However,
if your servlet container supports automatic reloading of servlets when you change the
class files, you have to make sure that the class containing the static methods is
loaded by a class loader in common (usually the system class loader that reads from the
CLASSPATH).
The reason for this is that classes (and therefore the static methods and variables
they
contain) are unique per class loader, not per JVM. It is entirely possible to have a
class like this:
import java.sql.Connection;
public class MyClass {
private static Connection conn = null;
public static Connection getConnection() {
return (conn);
}
public static void setConnection(Connection conn) {
this.conn = conn;
}
}
to share a JDBC connection globally (you would really want to use a connection pool for
this, but I'm illustrating the class loader issue here). The idea is that you'd have
an
initialization call somewhere:
Connection conn = ....; // Create a JDBC connection
MyClass.setConnection(conn);
and every servlet, in every application, could share this connection, like so:
Connection conn = MyClass.getConnection();
However, if the MyClass class is loaded by the class loader for a particular web
application (in servlet containers that support class reloading), it will *not* be
shared. The answer to this, as mentioned above, is to ensure that MyClass is loaded by
the system class loader instead. The details of how class loading is configured vary
by
servlet container, so you need to check the docs for yours.
Craig McClanahan
===========================================================================
To unsubscribe: mailto [EMAIL PROTECTED] with body: "signoff JSP-INTEREST".
FAQs on JSP can be found at:
http://java.sun.com/products/jsp/faq.html
http://www.esperanto.org.nz/jsp/jspfaq.html