J2EE:自定义标签属性的默认值

发布于 2024-09-03 01:26:32 字数 570 浏览 4 评论 0原文

因此,根据 Sun 的 J2EE 文档 (http ://docs.sun.com/app/docs/doc/819-3669/bnani?l=en&a=view),“如果不需要标签属性,则标签处理程序应提供默认值价值。”

我的问题是如何根据文档的描述定义默认值。代码如下:

<%@ attribute name="visible" required="false" type="java.lang.Boolean" %>
<c:if test="${visible}">
     My Tag Contents Here
</c:if>

显然,这个标签无法编译,因为它缺少标签指令和核心库导入。我的观点是,我希望“visible”属性默认为 TRUE。 “标签属性不是必需的”,因此“标签处理程序应该提供默认值”。我想提供一个默认值,那么我缺少什么?

非常感谢任何帮助。

So according to Sun's J2EE documentation (http://docs.sun.com/app/docs/doc/819-3669/bnani?l=en&a=view), "If a tag attribute is not required, a tag handler should provide a default value."

My question is how do I define a default value as per the documentation's description. Here's the code:

<%@ attribute name="visible" required="false" type="java.lang.Boolean" %>
<c:if test="${visible}">
     My Tag Contents Here
</c:if>

Obviously, this tag won't compile because it's lacking the tag directive and the core library import. My point is that I want the "visible" property to default to TRUE. The "tag attribute is not required," so the "tag handler should provide a default value." I want to provide a default value, so what am I missing?

Any help is greatly appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

宫墨修音 2024-09-10 01:26:32

我会回答我自己的问题。我突然顿悟,意识到 java.lang.Boolean 是一个类,而不是一个原语。这意味着该值可以为null,经过测试,这个值肯定是null。

当未定义值时,则传入 null。否则,该值就是传入的值。因此,声明属性后我要做的第一件事就是检查它是否为 null。如果它是 null,那么我知道没有传入值或有人向我传递了 null,并且应该将其转换为某个默认值:

<c:if test="${visible == null}"><c:set var="visible" value="${true}" /></c:if>

I'll answer my own question. I had an epiphany and realized that java.lang.Boolean is a class and not a primitive. This means that the value can be null, and after testing, this value most certainly is null.

When a value is not defined, then null is passed in. Otherwise, the value is whatever was passed in. So the first thing I do after declaring the attribute is to check if it's null. If it is null, then I know a value wasn't passed in or someone passed me null, and it should be converted to some default value:

<c:if test="${visible == null}"><c:set var="visible" value="${true}" /></c:if>
欢烬 2024-09-10 01:26:32

使用 JSP EL 和条件运算符,它会更简洁,甚至更短:

<c:set var="visible" value="${(empty visible) ? true : visible}" />

With JSP EL and conditional operator it's a little bit cleaner and even shorter:

<c:set var="visible" value="${(empty visible) ? true : visible}" />
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文