Show TOC

Procedure documentationUsing Declarations Locate this document in the navigation structure

 

You can use JSP declaration elements to declare variables or methods in your JSP page. The methods and variables that you define in the declaration are scoped at the current page level. That is, they are available only within the implementation class for the current JSP page.

Procedure

Defining Utility Methods in Your JSP

You can use declarations to define whichever utility methods you need for your JSP.

Syntax Syntax

You use declaration elements to define a formatName() method that does string tokenization:

  1. <%!
      private String formatName(String name){
        StringTokenizer tokenizer = new StringTokenizer(name, " ");
        StringBuffer formated = new StringBuffer();
    
        while(tokenizer.hasMoreTokens()){
          formatted.append(tokenizer.nextToken());
        }
        return formatted.toString();
      }
    %>
    
End of the code.

The method is then used within the following HTML code, in order to construct the filename of an image of the selected type of car to be displayed:

Syntax Syntax

  1. <td><img src="<%="images/" + formatName(vehicleType.getName()) + ".gif"%>" border="0"></td>
End of the code.

The method is then used within the following HTML code, in order to construct the filename of an image of the selected type of car to be displayed:

Providing Custom Initialization to Your JSP Page

Another example of using declaration elements is when you define a jspInit() method, in which you can get custom initialization parameters that you have defined in the deployment descriptor of your Web application. This method is called by the Web Container when it instantiates and initializes the implementation class of the JSP page.

Syntax Syntax

  1. <%! public void jspInit() {
        ServletContext context = getServletConfig().getServletContext();
        // Here you can get the custom parameters to initialize 
        // the JSP implementation class. It is done the same 
        // way as with servlets.
       }
    %>
    
End of the code.