InvoiceSelected.java

/*
  Copyright 2001, Pajato Systems Group
  Copyright 2001, Allaire Corporation
*/

package allaire.samples.invoice.taglib;

import java.io.IOException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

/**
 * The <inv:selectedItem> tag determines if the current invoice item is
 * the "selected" item (for the associated HTML select element).  It
 * must be embedded within a <inv:foreach> tag.
 */

public class InvoiceSelected extends TagSupport {

    public int doStartTag() throws JspException, JspTagException {

	int result = SKIP_BODY;

	// Determine if the parent tag is a <inv:foreach>
	String message;
	InvoiceIterator parent = (InvoiceIterator)
	    findAncestorWithClass( this, InvoiceIterator.class );
        if ( parent == null ) {

	    // It is not.  Throw an exception.
	    message =
		"The <inv:selectedItem> tag must be inside an <inv:foreach> tag.";
	    throw new JspTagException( message );
	}

	// Test the condition maintained inside the parent if tag to
	// determine the correct output value.
	String value;
	if ( parent.isSelectedItem() ) {
	    value = "selected";
	} else {
	    value = "";
	}

	try {
	    // Output the selected keyword.
	    pageContext.getOut().print( value );
	} catch ( IOException exc ) {
	    exc.printStackTrace();
	    throw new JspException( exc.getMessage() );
	}

	return result;
    }
}