【问题标题】:How to evaluate a dynamic/nested Spring property placeholder expression?如何评估动态/嵌套的 Spring 属性占位符表达式?
【发布时间】:2013-12-20 14:02:06
【问题描述】:

我正在开发一个 JSP 标记。这是开始循环遍历模型中项目的行:

<c:forEach var="toc" items="${requestScope[formKey].model.sharingTocs}">

但是代码已经过重构,所以模型路径(上面的model.sharingTocs)现在是动态的而不是固定的。它现在通过 JSP @attribute 传递到标签中:

<%@attribute name="path" required="true"%>

所以${path} 现在计算为"model.sharingTocs"

现在如何分配items

【问题讨论】:

    标签: spring jsp spring-mvc el spring-el


    【解决方案1】:

    嗯。好问题。

    这是一个解决方案:编写自定义 jstl 标记来评估 bean 的属性表达式:

    <mytag:eval bean="${requestScope['formKey']}" propertyExpression = "${path}" var="items" />
    

    和 ForEach:

    <c:forEach var="toc" items="${items}">
    </c:forEach>
    

    mytag:eval JSTL 标签示例代码(经典模型)

    public class EvalTag extends TagSupport
    {
    
        private Object bean;
        private String propertyExpression; //Ex: 'model.sharingTocs'
        private String var;
    
        //............
    
    
        @Override
        public int doEndTag() throws JspException {
            try {
    
                // Use reflection to eval propertyExpression ('model.sharingTocs') on the given bean
    
                Object propObject = SomeLibs.eval ( this.bean, this.propertyExpression);
    
                this.pageContext.getRequest().setAttribute(this.var, propObject);
    
                // You can add propObject into Other scopes too.
    
            } catch (Exception ex) {
                throw new JspTagException(ex.getMessage(), ex);
            }
            return EVAL_PAGE;
        }
    
          //............
          // SETTERS here
     }
    

    可用于评估 bean 的 propertyExpression 的库是 Apache bean utils。

    http://commons.apache.org/proper/commons-beanutils/apidocs/org/apache/commons/beanutils/package-summary.html#standard.nested

    【讨论】:

      【解决方案2】:

      如果你使用 spring,你可以使用 spring 标签库,它还假设你在一个 form:form 标签内。

      <%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
      
      <%@ attribute name="path" required="false" %>
      
      <spring:bind path="${path}">
          <c:forEach var="item" items="${status.value}">
                ${item}
          </c:forEach>
      </spring:bind>
      

      【讨论】:

        【解决方案3】:

        我问这个问题已经有一段时间了,但是(从那以后获得了新知识)我认为这应该可行:

        <c:set var="itemsPath" value="requestScope[formKey].${path}"/>
        <c:forEach var="toc" items="${itemsPath}">
        

        即设置一个包含项目完整路径的中间 JSTL 变量,并改为评估该变量。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-03-27
          • 2021-12-14
          • 1970-01-01
          • 2020-12-03
          • 2012-10-06
          相关资源
          最近更新 更多