Search code examples
jspapache-tiles

In Apache Tiles 2, what's the difference between importAttribute and useAttribute?


As far as I know both tags import variables from tiles context to JSP so variables are made visible in the JSP. Please elaborate the difference between importAttribute and useAttribute.


Solution

  • Apparently there's no difference between the two except that in useAttribute lets you specify the class name of the expected variable.

    Here's the code for importAttribute tag:

    @Override
    public void doTag() throws JspException {
        JspContext jspContext = getJspContext();
        Map<String, Object> attributes = model.getImportedAttributes(JspUtil
                .getCurrentContainer(jspContext), name, toName, ignore,
                jspContext);
        int scopeId = JspUtil.getScope(scopeName);
        for (Map.Entry<String, Object> entry : attributes.entrySet()) {
            jspContext.setAttribute(entry.getKey(), entry.getValue(), scopeId);
        }
    }
    

    and the code for useAttribute tag:

    @Override
    public void doTag() throws JspException {
        JspContext pageContext = getJspContext();
        Map<String, Object> attributes = model.getImportedAttributes(JspUtil
                .getCurrentContainer(pageContext), name, id, ignore,
                pageContext);
        if (!attributes.isEmpty()) {
            int scopeId = JspUtil.getScope(scopeName);
            pageContext.setAttribute(getScriptingVariable(), attributes
                    .values().iterator().next(), scopeId);
        }
    }