JSP Declarations
Home ] Up ] What's  a Java Server Page? ] How Does a JSP Work? ] Do JSPs Replace Servlets? ] JSP Expressions vs. Scriplets ] Conditional JSPs ] [ JSP Declarations ] A JSP Hit Counter ]

 

 

There is another kind of JSP tag: a JSP Declaration.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Declaration Example</title>
  </head>
  <body>
    
    <h1>JSP Declaration Example</h1>
    
    <%!
    private String countdown(int startValue)
    {
      String returnValue = "Counting... ";
      for (int count = startValue; count > 0; count--)
      {
        returnValue += count + " ";
      }
      return returnValue;
    }
    %>
    
    <h2>First countdown:</h2>
    <%= countdown(10) %>
    
    <h2>Second countdown:</h2>
    <%= countdown(15) %>
    
  </body>
</html>

A JSP declaration results in the code being placed inside the servlet class definition, but outside the class's methods.  In the above case, here's where the declaration code ended up in the generated servlet:

...
public final class Declaration_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {


    private String countdown(int startValue)
    {
      String returnValue = "Counting... ";
      for (int count = startValue; count > 0; count--)
      {
        returnValue += count + " ";
      }
      return returnValue;
    }
...

The above JSP page produces the following output:

 
The page was last updated February 19, 2008