java J2EE:自定义标记属性的默认值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2886533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
J2EE: Default values for custom tag attributes
提问by Nick
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."
因此,根据 Sun 的 J2EE 文档(http://docs.sun.com/app/docs/doc/819-3669/bnani?l=en&a=view),“如果不需要标记属性,则标记处理程序应提供默认值。”
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?
显然,这个标签不会编译,因为它缺少标签指令和核心库导入。我的观点是我希望“可见”属性默认为 TRUE。“标签属性不是必需的”,因此“标签处理程序应提供默认值”。我想提供一个默认值,那么我错过了什么?
Any help is greatly appreciated.
任何帮助是极大的赞赏。
回答by Nick
I'll answer my own question. I had an epiphany and realized that java.lang.Booleanis a class and not a primitive. This means that the value can be null, and after testing, this value most certainly is null.
我会回答我自己的问题。我顿悟了,意识到这java.lang.Boolean是一个类而不是一个原始的。这意味着该值可以为空,经过测试,该值肯定为空。
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:
当一个值未定义时,则传入 null。否则,该值就是传入的任何值。所以我在声明属性后做的第一件事就是检查它是否为 null。如果它是空的,那么我知道一个值没有传入或有人传给我空,它应该被转换为一些默认值:
<c:if test="${visible == null}"><c:set var="visible" value="${true}" /></c:if>
回答by G. Demecki
With JSP EL and conditional operator it's a little bit cleaner and even shorter:
使用 JSP EL 和条件运算符,它更简洁,甚至更短:
<c:set var="visible" value="${(empty visible) ? true : visible}" />

