Can I have a cache of dropdown data instead of getting it from DB on every request?
I am populating three dropdown menus using database stored procs. Each time the page is ca开发者_开发问答lled it executes the store procedure and populates the dropdowns. Doing so it takes much amount of time. Is there any other way that I can have a cache of the data and can use it rather than executing the stored procedure?
Store it in the application or session scope. Assuming that those dropdowns represent application wide constants, then you could use a ServletContextListener
for this. It get executed only one on webapp's startup.
E.g.
@WebListener
public class ApplicationDataConfigurator implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent event) {
Map<String, String> countries = populateAndGetItSomehow();
event.getServletContext().setAttribute("countries", countries);
// ...
}
@Override
public void contextDestroyed(ServletContextEvent event) {
// NOOP.
}
}
ServletContext attributes are also available in JSP EL the usual way:
<select name="countries">
<c:forEach items="${countries}" var="country">
<option value="${country.key}">${country.value}</option>
</c:forEach>
</select>
If you'd rather like to store it in the session instead, then use a preprocessing servlet instead which checks in doGet()
if they aren't already present in the current session and then populate it. You only need to realize that this may impact the total memory usage when it concerns large data.
精彩评论