代码之家  ›  专栏  ›  技术社区  ›  Rob Hruska MegalomanINA

在传递给JSP标记处理程序之前对变量求值

  •  3
  • Rob Hruska MegalomanINA  · 技术社区  · 15 年前

    在尝试使用自定义JSP标记库时,我在JSP中定义了一个变量,希望在传递到标记库之前对该变量进行求值。然而,我似乎无法让它发挥作用。以下是我的JSP的简化版本:

    <% int index = 8; %>
    
    <foo:myTag myAttribute="something_<%= index %>"/>
    

    doStartTag() 我的方法 TagHandler

    public int doStartTag() {
        ...
        out.println("Foo: " + this.myAttribute);
    }
    

    但是,我在最终标记中看到的输出是:

    Foo: something_<%= index %>
    

    而不是我想要的:

    Foo: something_8
    

    我的属性标记库定义为:

    <attribute>
        <name>myAttribute</name>
        <required>true</required>
    </attribute>
    

    我已尝试使用配置属性 rtexprvalue true false ,但两者都不起作用。是否有一种方法可以配置属性,以便在发送到处理程序之前对其进行评估?还是我完全错了?

    我对JSP标记比较陌生,所以我对解决这个问题的备选方案持开放态度。此外,我意识到在JSP中使用Scriptlet是不受欢迎的,但我在这里使用的是一些遗留代码,所以我现在有点拘泥于此。

    编辑:

    <foo:myTag myAttribute="something_${index}"/>
    

    这也不起作用-它只是输出 something_${index}

    3 回复  |  直到 15 年前
        1
  •  6
  •   Luke Woodward    15 年前

    我不相信你能用 <%= ... %> 在自定义标记的属性中,除非 < 是属性值的全部内容。以下内容对你有用吗?

    <% int index = 8; %>
    <% String attribValue = "something_" + index; %>
    
    <foo:myTag myAttribute="<%= attribValue %>"/>
    

    <% ... %>

        2
  •  2
  •   Amir Arad    14 年前

    为了保持JSP代码干净整洁,尽可能避免编写脚本。我认为这是最好的方法:

    <foo:myTag >
      <jsp:attribute name="myAttribute">
        something_${index}
      </jsp:attribute>
    </foo:myTag >
    

    如果标记还包含正文,则必须将其从

    <foo:myTag myAttribute="<%= attribValue %>">
      body
    </foo:myTag >
    

    <foo:myTag >
      <jsp:attribute name="myAttribute">
        something_${index}
      </jsp:attribute>
      <jsp:body>
        body
      </jsp:body>
    </foo:myTag >
    
        3
  •  0
  •   anon anon    15 年前

    <foo:myTag myAttribute="something_${index}"/>