JSP / JSTL: Always declare your beans where they are read / written

For an example, consider adding catalog entries to a request scoped map in order to cut down web service calls:

<wcf:set
target="${catalogEntryMap}"
key="${catalogEntryDetails.uniqueID}"
value="${catalogEntryDetails}"/>

Question: How could this error?

  1. The catalogEntryDetails variable could be empty, if so then the uniqueID property will also be empty. Resulting in the error: “Target is an instance of type Map, key cannot be empty”.
  2. The catalogEntryMap might not be set up, in which case we will see the error: “Target can be only an instance of type List or Map”.

Each one of these conditions requires a decision to be made…

Decision 1: What should we do if there is no catalogEntryMap?

The most sensible solution would be to create it. The simplest way to do this is to declare it using the <wcf:useBean /> tag, if catalogEntryMap doesn’t exist it will be created if it already exists it will be used as is.

<wcf:useBean
var="catalogEntryMap"
classname="java.util.HashMap"
scope="request"/>

Decision 2: What should we do if catalogEntryDetails or catalogEntryDetails.uniqueID is empty?

If this is the case, then we really don’t have anything to cache, it might point to wider problems but for this particular code, the sensible thing to do is to skip caching the data.

Therefore our resulting code is:

<wcf:useBean
var="catalogEntryMap"
classname="java.util.HashMap"
scope="request"/>

<c:if test="${
!empty catalogEntryDetails and
!empty catalogEntryDetails.uniqueID
}">

<wcf:set
target="${catalogEntryMap}"
key="${catalogEntryDetails.uniqueID}"
value="${catalogEntryDetails}"/>

</c:if>

Additional thoughts

Often we will split up our JSPs into fragments so that we can increase reuse, consider when doing this to always ensure that your fragment will work if included on an empty page, in other words: avoid making the fragment dependent on beans declared outside of it, just declare them within the fragment.

Stuart Wakefield

Software engineer and musician. I like graphic novels, illustration and games. I dabble with digital art and game development.

One thought on “JSP / JSTL: Always declare your beans where they are read / written

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s