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?
- 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”.
- 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.
good Explanation. Thank you so much. It helped me