pondělí 8. srpna 2005

How to detect bean property in JSTL?

I need detect java bean property inside JSP page. I didn't found any way how to solve this problem in JSTL or more precisely through expression language. In some cases view code iterates over returned model (java beans) , but doesn’t know which kind of bean is in model. It would be for example bean represents Car or House and every one has various properties to be displayed.

Consider this example:

 
   <c:forEach var="foo" items="${model}">         
   <TR>
     <TD id="P"><c:out value="${foo.price}"/></TD>
    </TR> 
 

We iterate over collection of model data and write price information to output. But it is possible that this instance of model hasn’t property price and code ${foo.price} causes exception. I don’t really know how to detect if bean has some property through expression language and therefore i made simply tag for this purpose (detect property on bean). This tag use reflection to determine if bean has appropriate property.

 
     protected int doStartTagInternal() throws Exception {
        .
        .
        .
        Field field[] = bean.getClass().getDeclaredFields();        
        for (int i = 0; i < field.length; i++) {
            if(prop.equals(field[i].getName())){
                pageContext.setAttribute("hasProperty", prop);
                break;
            }
        }        
        return SKIP_BODY;
     }
 

Simply modification of prevous example:

 
    <c:forEach var="foo" items="${model}">                 
    <TR>
       <t:hasProperty javaBean="${foo}" property="price" /> 
       <c:if test="${hasProperty != null}">
         <TD id="P">
           <c:out value="${foo.price}"/>   
          </TD>
        </c:if>
     </TR>   
 

I would like to notice that maybe would be better to define a function (by the help of JSP expression language) that can be invoked in an expression.