the Andrew Bailey

Dynamic Content

Someone I recently spoke to encouraged me to post some code here.

One of the things I have been implementing recently on my site is adding more dynamic content. By "dynamic", I mean changing the site without requiring an edit and rebuild of it. Stuff like header and footer text, passwords, titles, and various configuration values, but not stuff like blog posts or comments.

Step 1: I eventually decided that this would be way easier if I created a key/value pair table. Probably not the most kosher or enterprise-y (lacking a sequence), but for a table that will only hold 30 or so values read extremely infrequently, it will do.

CREATE TABLE KeyValue (
    key CHARACTER VARYING(1000) NOT NULL,
    "value" CHARACTER VARYING(65000) NOT NULL,
    CONSTRAINT KeyValue_PK PRIMARY KEY(key)
);

Step 2: read all values into a cache on startup. In my case, in a singleton EJB:

@Startup
@Singleton
public class UtilBean {
    private final Map keyValues=new HashMap();
    @PostConstruct
    public void init(){
        EntityManager em=persistenceUnit.createEntityManager();
        List<Keyvalue> kvs=em.createNamedQuery("Keyvalue.findAll", Keyvalue.class).getResultList();
        keyValues.clear();
        for (Keyvalue kv:kvs){
            em.refresh(kv);
            keyValues.put(kv.getKey(), kv.getValue());
        }
    }
    public String getValue(String key){
        return keyValues.get(key);
    }
    ...
}

Step 3: create a custom tag that grabs from said cache. Don't forget the tag library! (not shown)

// DBKV = DataBase Key Value
public class DBKV extends SimpleTagSupport {
    @EJB UtilBean util;
    private String key;
    public void setKey(String k){
        key=k;
    }
    @Override
    public void doTag() throws JspException, IOException {
        getJspContext().getOut().print(util.getValue(key));
    }
}

Step 4: Profit! Use in JSPs.

<t:DBKV key="page.side" />

Step 5: Create or wire some reset function of the site to the method that loads the KeyValues.

Step 6: Whenever you need to change some value in your page, run a DB update to change that KeyValue, and run that reset.

Posted under Programming.

You can't complain about this anymore. It's perfect!