2014-09-02 193 views
2

我有一個需要動態命名頁面作用域變量的標記。用動態名稱創建變量

someTag.tag

<%@ tag language="java" pageEncoding="UTF-8" dynamic-attributes="expressionVariables" %> 

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 

<%@ attribute name="expression" required="true" type="java.lang.String" %> 

<c:out value="${expression}" /> <%-- this is just an example, I use expressions differently, they are not jsp el actually --%> 

和用法示例

<%@ taglib prefix="custom_tags" tagdir="/WEB-INF/tags/custom_tags" %> 
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 

<c:set var="someAttr" value="someValue" /> 
<custom_tags:someTag expression="someMethod(#localAttr)" localAttr="${someAttr}" /> 

我需要把localAttr到標籤的頁面範圍,但JSTL <c:set var='${....}'... />不接受動態名。

我目前使用以下小腳本:

<c:forEach items="${expressionVariables}" var="exprVar"> 
    <% jspContext.setAttribute(((java.util.Map.Entry)jspContext.getAttribute("exprVar")).getKey().toString(), ((java.util.Map.Entry)jspContext.getAttribute("exprVar")).getValue()); %> 
</c:forEach> 

是否還有其他的方法來做到這一點?

+0

[動態變量名稱Java](http://stackoverflow.com/questions/5805843/dynamic-variable-names-java) – Raedwald 2014-09-02 11:45:24

+0

@Rededwald,這個問題是遠不及我的 – 2014-09-02 12:16:00

回答

1

您的技術是正確的。您可以使用自定義標籤來執行此操作,因爲您正在使用自定義標籤。您也可以使用您的技術,但通過這樣做使其更具可讀性/可維護性:

<c:forEach items="${expressionVariables}" var="exprVar"> 
    <c:set var="key" value="${exprVar.key}"/> 
    <c:set var="value" value="${exprVar.value}"/> 
    <% jspContext.setAttribute(jspContext.getAttribute("key"), jspContext.getAttribute("value")); %> 
</c:forEach> 

但顯然這只是一個偏好的事情。

如果您使用的是自定義標籤,這將減少在JSTL一行:

<custom_tags:loadPageVars expression="${expressionVariables}"/> 

,你會在expressionVariables只是環和設置的環境變量,就像你在你的做循環上面。

**

另外一個想法......如果你總是需要或者設定的PageScope變量權調用custom_tags前:someTag或調用它之後,你可以修改標籤的代碼,並可以設置上下文變量例如,TagSupport.doAfterBody()[if after]或BodyTagSupport.doInitBody()[if before]方法。