JSP Declaration Tag


This article is a series of JSP Tutorial. In this article, we will learn how to use a JSP declaration tag with an example.

JSP declarations basically allow you to declare a method in the JSP page, and then you can call them from the same JSP page.
So it's very useful like any normal code that you create. If you need to execute some code over and over again, you simply encapsulate it in a method declaration.

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"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <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:
    <%=firstName%>
    <br> Last Name:
    <%=lastName%>

    <br> Age:
    <%=age%>

    <br> Date of Birth:
   <%=dob%>

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

    <%! 
       String getLastName(){
          return "Fadatare";
       }
    %>


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

    <br> Last Name:
    <%= getLastName() %>
</body>
</html>
Let's invoke this JSP page from a Web browser, you see the table on a browser:

JSP Declarations - Best Practice

  • Minimize the number of declarations in a JSP
  • Avoid dumping thousands of lines of code in a JSP
  • Refactor this into a separate Java class … make use of MVC

In the next article, we will learn what are JSP implicit objects with an example.

Comments