Using Implicit Cooperation Through Variables

Many JSTL actions cooperate implicitly through JSP scoped variables; one action exposes the result of its processing as a variable in one of the JSP scopes and another action uses the variable as its input. This type of cooperation is simple yet powerful.

All that is required is that the tag handler that exposes the data saves it in one of the JSP scopes, for instance using the PageContext.setAttribute( ) method:

public class VariableProducerTag extends SimpleTagSupport {
    private String var;
    private int scope = PageContext.PAGE_SCOPE;
  
    public void setVar(String var) {
        this.var = var;
    }
  
    public void setScope(String scope) {
        if ("page".equals(scopeName)) {
            scope = PageContext.PAGE_SCOPE;
        }
        else if ("request".equals(scopeName)) {
            scope = PageContext.REQUEST_SCOPE;
        }
        else if ("session".equals(scopeName)) {
            scope = PageContext.SESSION_SCOPE;
        }
        else if ("application".equals(scopeName)) {
            scope = PageContext.APPLICATION_SCOPE;
        }
    }
  
    public void doTag(  ) {
        // Perform the main task for the action
        ...
        getJspContext(  ).setAttribute(var, result, scope);
        JspFragment body = getJspBody(  );
        if (body != null) {
            body.invoke(null);
        }
    }
}

Here an attribute named var lets the page author specify the name of the variable. Even though this isn’t strictly a requirement (cooperating tags could be designed to use a predefined, hardcoded variable name), it’s the most flexible approach. The attribute name can be anything, but var is the name used by all JSTL actions. ...

Get JavaServer Pages, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.