Thanks to Christopher, Harish, Kevin and Stephen for answering my question. The solution to my problem was the ServletContext.
 
So that anyone interested in having global objects doesn't have to spend all the time I spent on this, I publish the solution here. There are three things that you must set up to make this work:
 
1. The Global Object - The object you want to be accessible by the servlets.
2. Setup web.xml - This is the "link" to your global object.
3. Access the Data in the Global Object
 
 
1. The Global Object
 
Here's a class/object named SomeName, which I wish to be accessed globally:
 
public class SomeName
{
  static final String StaticTextString="Yep, it works.";
 
  static final String ToText(byte Nr)
  {
    String ReturnValue;
 
    switch (Nr)
    {
      case 1:  ReturnValue="One";
               break;
      case 2:  ReturnValue="Two";
               break;
      default: ReturnValue="Not One or Two";
    }
    return(ReturnValue);
  }
}
 
2. Setup web.xml
 
web.xml can be found in your application directory. Add the following parameter Name ( SomeNameObj ) & Value ( SomeName ) in web.xml:
 
 <context-param>
   <param-name>SomeNameObj</param-name>
   <param-value>SomeName</param-value>
 </context-param>
3. Access the Data in the Global Object
 
The following is a Servlet named GetValues that access the static/final value and method of the global SomeName object: (through the name SomeNameObj )
 
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
 
public class GetValues extends HttpServlet
{
  public void doGet(HttpServletRequest Req, HttpServletResponse Res) throws ServletException, IOException
  {
    Res.setContentType("text/plain");
 
    PrintWriter Out=Res.getWriter();
 
    ServletContext ServletContextData=getServletContext();
    Out.println("Static/Final Variable: " + ((SomeName) ServletContextData.getAttribute("SomeNameObj")).StaticTextString);
    for (byte Counter=1;Counter<=3;Counter++)
      Out.println("Static/Final Method: " + ((SomeName) ServletContext.getAttribute("SomeNameObj")).ToText(Counter));
  }
}
 
Don't forget to cast the object that gets returned by .getAttribute, as well... the parentheses are important.
 
I hope that someone finds this information useful. I'm certainly happy with this solution.
 
Cheers,
Gert

Reply via email to