1/07/2009

ServletContext

A javax.servlet.ServletContext object is created per application.

If you set the "distributable" tag in the web.xml of an application, which means the application can be distributed to multiple JVMs, there will be one context instance for each virtual machine.

In a distributed environment, using attributes of a context object for global information is not recommended. Using a database is recommended.

The javax.servlet.ServletConfig#getServletContext method returns a reference to the ServletContext.

<Sample>
public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {
        String parameter =
            this.getServletConfig().getServletContext()
            .getInitParameter("dateformat");
        SimpleDateFormat fmt = new SimpleDateFormat(parameter);
        PrintWriter out = res.getWriter();
        out.println("<html><body>");
        out.println(fmt.format(new Date()));
        out.println("</body></html>"); 
}

In JSP files, one of the implicit objects called "application" can be used.
<Sample>
    application.getInitParameter("dateformat");

In classes that implement the ServletContextListener, use a ServletContextEvent object.
<Sample>
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext context = sce.getServletContext();
    }

Context initial parameters setting

You can define init parameters in the web.xml of an application.
You can use multiple context-param tags.

<context-param>
    <param-name>dateformat</param-name>
    <param-value>yyyy/MM/dd</param-value>
</context-param>