代码之家  ›  专栏  ›  技术社区  ›  michael nesterenko

使用动态名称创建变量

  •  2
  • michael nesterenko  · 技术社区  · 10 年前

    我有一个标记,需要具有动态命名的页面范围变量。

    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='${....}'... /> 不接受动态名称。

    我目前使用以下scriptlet:

    <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>
    

    有没有其他方法可以做到这一点?

    1 回复  |  直到 10 年前
        1
  •  1
  •   alfreema    10 年前

    你的技术是正确的。您可以使用自定义标记来执行此操作,因为您使用的是自定义标记。您也可以使用您的技术,但通过执行以下操作使其更加可读/可维护:

    <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}"/>
    

    您只需循环表达式variables并设置上下文变量,就像在上面的For循环中所做的那样。

    **

    还有一个想法。。。例如,如果总是需要在调用custom_tags:someTag之前或调用它之后设置pageScope变量,则可以修改该标记的代码,并在TagSupport.doAfterBody()[if-after]或BodyTagSupport.doInitBody()[if-before]方法中设置上下文变量。