FibonnaciCalculateTag.java.

Enterprise Java
Tag Libraries: JSPs in the Enterprise
by Dion Almaer
Listing 7. FibonnaciCalculateTag.java.


package com.customware.fib;

import java.io.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

/**
 * This class defines a custom JSP tag that handles fibonnaci.
 * Usage:<BR>
 * <fib:calculate number="2"><BR>
 * [this is part of the body and will be deleted. used for designers]<BR>
 * </fib:calculate>
 */

public class FibonnaciCalculateTag extends TagSupport {
  private int number = 0;

  // -- Setters and getters for the attributes
  public void setInput(String input) {
     try {
             this.number = Integer.parseInt( input.trim() );
     } catch (NumberFormatException e) { }
  }

  public int getInput() { return this.number; }

  // -- TAG stuff
  public int doStartTag() throws JspException {
    return SKIP_BODY;
  }

  public int doEndTag() throws JspException {
    // Reformat the body with the calculation inputted
    Fibonnaci fib = new Fibonnaci();
    int output = fib.calculateFibonacci( this.getInput() );

    // Write contents of 'output' to the parent's out stream.
    try {
      pageContext.getOut().println( output );
    } catch (IOException ioe) {}

    return EVAL_PAGE;
  }

}

About the Author

Dion Almaer is a senior consultant for CustomWare in Boulder, CO. He can be reached at [email protected].