一尘不染

如何评估动态/嵌套Spring属性占位符表达式?

jsp

我正在处理JSP标签。这是开始循环浏览模型中各项的 行:

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

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

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

因此${path}现在评估为"model.sharingTocs"

items现在如何分配?


阅读 218

收藏
2020-06-10

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

可以用来评估property的lib是Apache bean utils。

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

2020-06-10