Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking attribute exists in JSP

Tags:

jsp

jstl

jsp-tags

I have some classes which extends a superclass, and in the JSP I want to show some attributes of these classes. I only want to make one JSP, but I don't know in advance if the object has an attribute or not. So I need a JSTL expression or a tag which checks that the object I pass has this attribute (similar to in operator in javascript, but in the server).

<c:if test="${an expression which checks if myAttribute exists in myObject}">
    <!-- Display this only when myObject has the atttribute "myAttribute" -->
    <!-- Now I can access safely to "myAttribute" -->
    ${myObject.myAttribute}
</C:if>

How can I get this?

Thanks.

like image 968
Javi Avatar asked Mar 26 '10 10:03

Javi


3 Answers

Make use of JSTL c:catch.

<c:catch var="exception">${myObject.myAttribute}</c:catch>
<c:if test="${not empty exception}">Attribute not available.</c:if>
like image 107
BalusC Avatar answered Nov 10 '22 06:11

BalusC


You can readily create a custom function to check for the property, as per vivin's blog post.

In short, if you already have your own taglib its just a matter of creating a static 'hasProperty' method...

import java.beans.PropertyDescriptor;
import org.apache.commons.beanutils.PropertyUtils;

...

public static boolean hasProperty(Object o, String propertyName) {
    if (o == null || propertyName == null) {
        return false;
    }
    try
    {
      return PropertyUtils.getPropertyDescriptor(o, propertyName) != null;
    }
    catch (Exception e)
    {
      return false;
    }
}

...and adding five lines to your TLD...

<function>
    <name>hasProperty</name>
    <function-class>my.package.MyUtilClass</function-class>
    <function-signature>boolean hasProperty(java.lang.Object,
        java.lang.String)
    </function-signature>
</function>

... and calling it in your JSP

<c:if test="${myTld:hasProperty(myObject, 'myAttribute')}">
  <c:set var="foo" value="${myObject.myAttribute}" />
</c:if>
like image 42
sbk Avatar answered Nov 10 '22 06:11

sbk


The accepted answer may have some side effects when I just want to test if the object has a field, but do not want to output the value of the field. In the mentioned case, I use the snippet below:

 <c:catch var="exception">
        <c:if test="${object.class.getDeclaredField(field) ne null}">            
        </c:if>
 </c:catch>

hope this helps.

like image 4
Chaojun Zhong Avatar answered Nov 10 '22 06:11

Chaojun Zhong