Define JSP Declaration with example

Define JSP Declaration with example

A JSP declaration is enclosed within <%! %>. This tag allows you to declare variables and methods that can be used elsewhere in the JSP file. These declarations are placed outside of the _jspService method, meaning they are part of the JSP page’s servlet class but not part of the main request processing logic.

JSP declaration

Here’s a simple example of using a JSP to define a method and a variable:

Example

jsp
<%@ page language="java" %>
<%! 
    // Declaration of an instance variable
    private int counter = 0;
    
    // Declaration of a method
    public int getNextCounterValue() {
        return ++counter;
    }
%>

<html>
<head>
    <title>JSP Declaration Example</title>
</head>
<body>
    <h1>Counter Value: <%= getNextCounterValue() %></h1>
</body>
</html>

Explanation of the JSP

1.  Variable Declaration :

  •     jsp private int counter = 0;
  •     This line declares a private integer variable counter and initializes it to 0.

2.  Method Declaration :

  •     jsp
  •     public int getNextCounterValue() {
  •         return ++counter; }
  •     – This method increments the counter variable and returns its new value.

3.  Using the Method in JSP :

  •     jsp
  •   <h1>Counter Value: <%= getNextCounterValue() %></h1>
  •   The method getNextCounterValue() is called within an expression tag <%= %>, which outputs the result to the client.

Homepage

Readmore