Question

I have a lot of dropdown menus in my application. The contents of these dropdown menus is read from the database.

Currently, to avoid pulling these values back every-time I want to use them, I pull them back once when I first need them and store them in the session after that.

This is not good. I do want to be storing them in the session as there are a number of them, and I think it's a bit, well, clunky. I would like to ideally (assuming you don't disagree), store these 'constants' (they aren't traditional constants, but they won't change for the duration of the deployment), in the application scope, so they need only be pulled back from the database once per deployment.

What I'm wondering is, what is the way to store these dropdown values in the application context at startup?

Was it helpful?

Solution

There is an interface by the name of ServletContextListener which provides a hook into the initialization of your servlet context. The ServletContext is your application's context, ie. its configuration.

One way to do what you are describing is to implement this interface and register the ServletContextListener either in web.xml or by annotating the class with @WebListener.

In the contextInitialized() method, you would pull the constants, set them up in any way you needed to and then put them in the ServletContext as attributes

@WebListener
public static class MyListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext context = sce.getServletContext();
        int someConstant = 42;
        context.setAttribute("myConstant", someConstant);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        ...
    }
}

You can then access these constants anywhere you have access to the ServletContext.

In a Servlet or Filter, you can get it from the ServletRequest

HttpServletRequest request = ....;
request.getServletContext();

You also have access to it from the init() methods of Servlet and Filter if you want to add more attributes there.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top