JSP中存在Checking属性

问题描述 投票:39回答:5

我有一些扩展超类的类,在JSP中我想展示这些类的一些属性。我只想制作一个JSP,但我事先并不知道该对象是否具有属性。所以我需要一个JSTL表达式或一个标签来检查我传递的对象是否具有此属性(类似于javascript中的运算符,但在服务器中)。

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

我怎么能得到这个?

谢谢。

jsp jstl jsp-tags
5个回答
58
投票

利用JSTL c:catch

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

15
投票

根据vivin's blog post,您可以轻松创建自定义函数来检查属性。

简而言之,如果您已经拥有自己的taglib,那么只需要创建一个静态的'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;
    }
}

...并在您的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>

...并在JSP中调用它

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

2
投票

只是更详细(典型?)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}

正如Shervin在BalusC的回答中所指出的那样,这可能不是最干净的解决方案,但正如BalusC所回答的那样“到目前为止,这是实现奇怪要求的唯一途径”。

资源


2
投票

当我只想测试对象是否有字段但不想输出字段的值时,接受的答案可能会有一些副作用。在上述情况下,我使用下面的代码段:

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

希望这可以帮助。


1
投票

你的意思是这样的:

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

或其他变体

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

如果它是一个列表,你可以做

<c:if test="#{not empty myObject.myAttribute}">
© www.soinside.com 2019 - 2024. All rights reserved.