Earlier yesterday I remembered a "pattern" that I had found while developing the last web application I worked on. I actually found it in 2002 and implemented a fix, but never really thought much about it. Who knew it was a "pattern"? Yesterday, it all came together and I realised that it was a pattern and that I should quickly "put it out there" for others to find as well.
Last night I put it off until it was to late and ended up deciding to sleep on it. Which was probably a good thing, because I would have been ridiculed by the community (what little of the community that actually knows I exist). This pattern is so obvious that everyone has to have about 30 different ways that it has been implemented.
The first implementation that I came up with used a taglib. How silly am I... because that whole taglib is no longer needed with the advent of EL. Which is the reason why I would have been ridiculed, I was going to tell the world of my fabulous taglib only to realize last night in bed that EL would do the same thing without all of the fuss. So, with that, here is my simple SelectDisplay Pattern.
The Problem:
When displaying results from entering a form, the display values of a select (or drop down list) need to be displayed instead of the value that is stored in the database. Generally, these are foriegn keys to lookup tables that store a key value pair for often used values. States of the United States are an excellent example.
The Solution:
Select all of the rows from the lookup table and store the values in the application context of the web application server as a Map. You only do this once at startup. If the values of the lookup table are dynamic, then you will need to overwrite the cache for that lookup table whenever a save is made. When you need to display the value of the lookup you should use the following EL:
${statesOfAmerica[yourForm.stateId]}
The above EL will essentially make this call:
stateId = ((YourForm) request.getAttribute("yourForm")).getStateId();
((Map) pageContext.getServletContext()
.getAttribute("statesOfAmerica"))
.get(stateId)
Like I said, not much of a "pattern". The plus side is that you don't have to do joins on your lookup tables in the database. You are allowing the application server to do the joins which isn't neccessarily a bad thing. Also, this is repeatable for any lookup you may have.
The initial implementation used an Iterator over a List. The next version the taglib iterated over the List once and pushed everything into a Map and used the Map for future calls. Both versions were fronted by a taglib. My next implementation will use only EL and will directly load the Map at startup.
Posted by carl at March 25, 2004 09:37 AM
Comments