J2EE:自定义标签属性的默认值
因此,根据 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会回答我自己的问题。我突然顿悟,意识到
java.lang.Boolean
是一个类,而不是一个原语。这意味着该值可以为null,经过测试,这个值肯定是null。当未定义值时,则传入 null。否则,该值就是传入的值。因此,声明属性后我要做的第一件事就是检查它是否为 null。如果它是 null,那么我知道没有传入值或有人向我传递了 null,并且应该将其转换为某个默认值:
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:
使用 JSP EL 和条件运算符,它会更简洁,甚至更短:
With JSP EL and conditional operator it's a little bit cleaner and even shorter: