Vì vậy, tôi không thể tìm ra cách để thêm điều này vào chỉ thị attribute
; có vẻ như chỉ thị không hỗ trợ chức năng này. Tuy nhiên, tôi có thể tạo thẻ đóng gói logic <c:if>...</c:if>
. Tôi đã phải viết thẻ trong Java vì không có cách nào (mà tôi biết) để sử dụng một giá trị thuộc tính như một tên biến.
Đầu tiên tôi đã viết các tập tin thẻ như là một lớp 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;
}
}
Sau đó, tôi đã thực hiện một tập tin 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>
Sau đó, tôi làm một thẻ tùy chỉnh có sử dụng thẻ này:
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}
Sau đó tôi thực hiện một trang để kiểm tra thẻ tôi vừa tạo:
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/>
Và điều đó đã cho tôi:
helloThar tùy chọn khỉ
helloThere khỉ
helloYou 17
Nguồn
2010-06-29 00:46:16