JSP Declaration Tag Syntax with Example

The JSP declaration tag is used to declare fields and methods.

The code written inside the JSP declaration tag is placed outside the service() method of the auto-generated servlet.
All JSP Examples at JSP Source Code Examples

The Syntax of JSP Declaration Tag

<%!  Declaration %>

JSP Declaration Tag Example

Let's demonstrates how to use JSP declaration tag to declare fields and methods with an example:
<%@page import="java.time.LocalDate"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<!DOCTYPE html>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
    <h1>Using variables in declaration tag</h1>
    <%!String firstName = "Ramesh";%>
    <%!String lastName = "Fadatare";%>
    <%!int age = 28;%>
    <%!LocalDate dob = LocalDate.of(1991, 03, 24);%>

    <br> First Name:
    <br> Last Name:

    <br> Age:

    <br> Date of Birth:

    <h1>Using methods in declaration tag</h1>
        String getFirstName(){
            return "Ramesh";

       String getLastName(){
          return "Fadatare";

    <br> First Name:
    <%= getFirstName() %>

    <br> Last Name:
    <%= getLastName() %>
Let's invoke this JSP page from a Web browser, you see the table on a browser:
All JSP Examples at JSP Source Code Examples

Free Spring Boot Tutorial - 5 Hours Full Course

Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course