-
1. Re: Creating Objects in Application Scope at Deploy Time
jcordes Nov 3, 2003 10:45 AM (in response to raphead)It can be done by writing a javax.servlet.ServletContextListener. This listener is notified upon creation of the context (and when it's destroyed). You have to pass the parameters as context-params, though (the listener-element in web.xml has no param-children). All together:
web.xml
<context-param>
<param-name>i18nResources</param-name>
<param-value>/WEB-INF/application.properties</param-value>
</context-param>
<listener-class>MyListener</listener-class>
listener:
public class MyListener implements ServletContextListener {
public void contextDestroyed(ServletContextEvent e) {
}
public void contextInitialized(ServletContextEvent e) {
ServletContext ctx = e.getServletContext()
String pathToProperties = ctx.getInitParameter("i18nResources");
...
ctx.setAttribute("i18nResources", resources);
}
}
Then you gain access to your resources by calling request.getSession().getServletContext().getAttribute("i18nResources"); (or even easier with ${i18nResources} if your using jstl with el-tags ;-)).
HTH,
Jochen. -
2. Re: Creating Objects in Application Scope at Deploy Time
raphead Nov 7, 2003 5:52 AM (in response to raphead)Hi, thanks for that hint! Seems really smooth with regard to integration. I think when I'm starting with Servlets, I'll do this.
For now, as I want to stick with JSPs at first and I found a solution: I used a singleton which gets not stored in a static field but in the application scope:
public class ApplicationGlobalData
{
public String applicationUri = "";
public String applicationPath = "";
private ApplicationGlobalData()
{
}
private ApplicationGlobalData(HttpServletRequest request)
{
init(request);
}
private synchronized void init(HttpServletRequest request)
{
if (request.getServerPort() == 433)
{
applicationPath += "https://"+request.getServerName();
} else {
applicationPath += "http://"+request.getServerName();
if (request.getServerPort() != 80)
{
applicationPath += ":"+request.getServerPort();
}
}
applicationPath += request.getContextPath()+"/";
applicationUri += applicationPath+"index.jsp";
}
public static ApplicationGlobalData getInstance(HttpServletRequest request, ServletContext application)
{
ApplicationGlobalData applicationGlobalData;
if(application.getAttribute("ApplicationGlobalData") == null)
{
applicationGlobalData = new ApplicationGlobalData(request);
application.setAttribute("ApplicationGlobalData", applicationGlobalData);
System.out.println("---------------> INIT ApplicationGlobalData");
} else {
applicationGlobalData = (ApplicationGlobalData)application.getAttribute("ApplicationGlobalData");
}
return applicationGlobalData;
}
}
Disadvantage: For each request the Constructor has to check whether already an Object exists.