2014-09-02 280 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]方法。