[ Team LiB ] Previous Section Next Section

23.2 Integrating Custom Conditional Actions

The JSTL core library contains one, generic conditional action: <c:if>. This action handles all conditions that can be expressed as Boolean EL expressions, but you often need more than that. Examples from Part II of this book include: testing if a mail address has valid syntax and if the current user belongs to a specific group.

To help developing this type of conditional custom action, JSTL includes a base class called javax.servlet.jsp.jstl.core.ConditionalTagSupport:

public abstract class ConditionalTagSupport
  extends javax.servlet.jsp.tagext.TagSupport

It contains the following public methods:

protected abstract boolean condition(  ) throws JspTagException
public void setVar(String var)
public void setScope(String scope)
public int doStartTag(  ) throws JspException
public void release(  )

The doStartTag( ) implementation calls the condition( ) method and takes care of saving the result if the var and scope attributes are set.

By extending this class and providing an implementation of the condition( ) and setter methods for all attributes you need, you get a conditional action that is consistent with the semantics of the JSTL version.

Example 23-1 shows the tag handler class for <ora:ifUserInRole>, which takes advantage of this JSTL support class.

Example 23-1. Tag handler for a conditional action
package com.ora.jsp.tags;
  
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.jstl.core.*;
import org.apache.taglibs.standard.lang.support.*;
  
public class IfUserInRoleTag extends ConditionalTagSupport {
    private String value;
  
    public void setValue(String value) {
        this.value = value;
    }
  
    public boolean condition(  ) throws JspTagException {
        HttpServletRequest request = 
            (HttpServletRequest) pageContext.getRequest(  );
        return request.isUserInRole(value);
    }
}

The only method of interest is condition( ). All it does is calling the isUserInRole( ) method provided by the HttpServletRequest class. It's that simple.

You may wonder if there's a similar support class for custom actions to be used within a <c:choose> block. The answer is no. Allowing custom actions as alternatives to <c:when> can cause strange side-effects, so instead, the recommended model is to use a conditional action, save the result as a variable, and test the variable value with a <c:when> action:

<ora:ifUserInRole value="admin" var="isAdmin" />
<c:choose>
  <c:when test="${isAdmin}">
    ...
  </c:when>
  <c:otherwise>
    ...
  </c:otherwise>
</c:choose>

It's a little bit more work, but it's a clean solution.

    [ Team LiB ] Previous Section Next Section