tag que ejemplo custom jsp jstl jsp-tags

que - tag jsp java



El atributo de comprobaciĆ³n existe en JSP (5)

Tengo algunas clases que extienden una superclase, y en el JSP quiero mostrar algunos atributos de estas clases. Solo quiero hacer una JSP, pero no sé de antemano si el objeto tiene un atributo o no. Entonces necesito una expresión JSTL o una etiqueta que compruebe que el objeto que paso tiene este atributo (similar a en el operador en javascript, pero en el servidor).

<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>

¿Cómo puedo conseguir esto?

Gracias.


Haga uso de JSTL c:catch .

<c:catch var="exception">${myObject.myAttribute}</c:catch> <c:if test="${not empty exception}">Attribute not available.</c:if>


Puede crear fácilmente una función personalizada para verificar la propiedad, según la publicación de blog de vivin .

En resumen, si ya tiene su propio taglib, solo se trata de crear un método estático ''hasProperty'' ...

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; } }

... y agregando cinco líneas a su 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>

... y llamarlo en tu JSP

<c:if test="${myTld:hasProperty(myObject, ''myAttribute'')}"> <c:set var="foo" value="${myObject.myAttribute}" /> </c:if>


Solo un uso más detallado (¿típico?) De la gran respuesta de BalusC

<%-- [1] sets a default value for variable "currentAttribute" [2] check if myObject is not null [3] sets variable "currentAttribute" to the value of what it contains [4] catches "property not found exception" if any - if exception thrown, it does not output anything - if not exception thrown, it outputs the value of myObject.myAttribute --%> <c:set var="currentAttribute" value="" /> <%-- [1] --%> <c:if test="${not empty myObject}"> <%-- [2] --%> <c:set var="currentAttribute"> <%-- [3] --%> <c:catch var="exception">${myObject.myAttribute}</c:catch> <%-- [4] --%> </c:set> </c:if> <%-- use the "currentAttribute" variable without worry in the rest of the code --%> currentAttribute is now equal to: ${currentAttribute}

Como lo señaló Shervin en los comentarios de la respuesta de BalusC, probablemente esta NO sea la solución más limpia, pero BalusC respondió: "hasta ahora, esa es la única manera de lograr un requisito extraño".

Recursos


Te refieres a algo como esto:

<c:if test="${not null myObject.myAttribute}"> <!-- Now I can access safely to "myAttribute" --> </C:if>

u otra variante

<c:if test="${myObject.myAttribute != null}"> <!-- Now I can access safely to "myAttribute" --> </C:if>

Si es una lista que puedes hacer

<c:if test="#{not empty myObject.myAttribute}">


la respuesta aceptada puede tener algunos efectos secundarios cuando solo quiero probar si el objeto tiene campo, pero no quiero mostrar el valor del campo. En los casos mencionados, utilizo el golpe de fragmento:

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

espero que esto ayude.