Conditionally set an attribute on an element with JSP Documents (JSPX)
In HTML forms, buttons can be disabled by defining the "disabled" attribute on them, with any value:
<button name="btn1" disabled="disabled">Hello</button>
If a button is to be enabled, the attribute should not exist as there is no defined value that the disabled attribute can be set to that would leave the button enabled.
This is causing me problems when I want to enable / disable buttons when using JSP Documents (jspx). As JSP documents have to be well-formed XML documents, I can't see any way of conditionally including this attribute, as something like the following isn't legal:
<button name="btn1" <%= (isDisabled) ? "disabled" : "" %/> >Hello</button>
While I could replicate the tag twice using a JSTL if tag to get the desired effect, in my specific case I have over 15 attributes declared on the button (lots of javascript event handler attributes for AJAX) so duplicating the tag is going to make the JSP very messy.
How can I solve this problem, without sacrificing the readability of the JSP? Are there any custom tags that can add attributes to the parent by manipulating the output DOM?
I use a custom JSP tag with dynamic attributes. You use it like this:
<util:element elementName="button" name="btn1" disabled="$(isDisabled ? 'disabled' : '')"/>
Basically, what this tag does is generate an XML element with elementName and puts all attributes present in the tag, but skips the empty ones.
The tag itself is pretty easy to implement, my implementation is just 44 lines long.
You can use the <jsp:text>
tag to solve this problem using valid XML:
<jsp:text><![CDATA[<button name="btn1"]]></jsp:text>
<c:if test="${isDisabled}"> disabled="disabled"</c:if>
>
Hello!
<jsp:text><![CDATA[</button>]]></jsp:text>
This is obviously more verbose than some other solutions. But it's completely self-contained : no custom tags required. Also, it scales easily to as many attributes as you need.
@alex great solution to use the ternary operator. I add some of my example, that thanks to you, I just changed the result of the condition, if true, writes the attribute, otherwise not write anything
to populate the list and select the value used, avoiding c:if
<select id="selectLang" name="selectLang" >
<c:forEach var="language" items="${alLanguages}" >
<option value="${language.id}" ${language.code == usedLanguage ? 'selected' : ''} >${language.description}</option>
</c:forEach>
to check at start a radio button to avoiding c:if:
<input type="radio" id="id0" value="0" name="radio" ${modelVar == 0 ? 'checked' : ''} />
<input type="radio" id="id1" value="1" name="radio" ${modelVar == 1 ? 'checked' : ''} />
<input type="radio" id="id2" value="2" name="radio" ${modelVar == 2 ? 'checked' : ''} />
链接地址: http://www.djcxy.com/p/76582.html
上一篇: 在GAE / J上使用jsp时出错500