Quindi non è stato possibile trovare un modo per aggiungerlo alla direttiva attribute
; sembra che la direttiva non supporti questa funzionalità. Tuttavia, ero in grado di creare un tag che incapsula la logica <c:if>...</c:if>
. Ho dovuto scrivere il tag in Java poiché non c'è modo (che io sappia) di usare un valore di attributo come nome di variabile.
Per prima cosa ho scritto il file di tag come una classe Java:
DefaultTag.java
public class DefaultTag extends BodyTagSupport {
private String var;
private Object value;
//for tag attribute
public void setVar(String var) {
this.var = var;
}
//for tag attribute
public void setValue(Object value) {
this.value = value;
}
public int doEndTag() throws JspException {
Object oldValue = pageContext.getAttribute(var);
Object newValue;
if(value != null) {
newValue = value;
}
else {
if(bodyContent == null || bodyContent.getString() == null) {
newValue = "";
}
else {
newValue = bodyContent.getString().trim();
}
}
if(oldValue == null) {
pageContext.setAttribute(var, newValue);
}
else if(oldValue.toString().trim().length() == 0) {
pageContext.setAttribute(var, newValue);
}
return EVAL_PAGE;
}
}
Poi ho fatto un file tld
:
utils.tld:
<?xml version="1.0" encoding="ISO-8859-1"?>
<taglib xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
version="2.1">
<tlib-version>2.0</tlib-version>
<short-name>utils</short-name>
<uri>http://utils</uri>
<tag>
<name>default</name>
<tag-class>com.mystuff.mvc.tag.DefaultTag</tag-class>
<body-content>JSP</body-content>
<attribute>
<name>var</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>value</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
poi ho fatto un tag personalizzato che utilizza questo tag:
defaultTest.tag
<%@ taglib prefix="utils" uri="/WEB-INF/tlds/utils.tld" %>
<%@ attribute name="value" required="true"%>
<%@ attribute name="optValue" required="false"%>
<utils:default var="optValue" value="optional monkeys"/>
${value} ${optValue}
Dopo che ho fatto una pagina per testare il tag appena creata:
tagTest. jsp
<mystuff:defaultTest value="helloThar" /><br/><br/>
<mystuff:defaultTest value="helloThere" optValue="monkeys" /><br/><br/>
<mystuff:defaultTest value="helloYou" optValue="${1 + 2 + 4 + 10}" /><br/><br/>
E che mi ha dato:
helloThar scimmie opzionali
helloThere scimmie
helloYou 17
fonte
2010-06-29 00:46:16