JSP Scriptlet tag and Declaration tag
JSP Scriptlet Tag (<% %>):
- Contains Java code that gets executed each time the JSP page is requested.
- The code within a scriptlet is inserted into the _jspService method.
- Typically used for control flow statements (loops, conditionals) and for generating dynamic content.
JSP Declaration Tag (<%! %>):
- Contains Java code that declares variables and methods.
- The code within a declaration tag is inserted outside of the _jspService method, into the class definition.
- Used for declaring variables, methods, and initialization code that needs to be executed only once during the lifecycle of the servlet.
Table of Contents
Simple Example to Illustrate the Differences
Let’s create a simple JSP page that uses both scriptlet and declaration tags.
JSP Scriptlet Example
jsp
<%@ page language="java" %>
<html>
<head>
<title>JSP Scriptlet Example</title>
</head>
<body>
<%
// Scriptlet tag: This code will be executed for each request
int counter = 1;
out.println("Scriptlet Counter Value: " + counter);
%>
</body>
</html>
In this example:
- The variable counter is declared and initialized within a scriptlet tag.
- The value of counter is printed using out.println.
- This code runs every time the JSP page is requested, so counter will always be 1.
Example
JSP Declaration Example
jsp
<%@ page language="java" %>
<%!
// Declaration tag: This code is part of the servlet class, not the _jspService method
private int counter = 0;
public int incrementCounter() {
return ++counter;
}
%>
<html>
<head>
<title>JSP Declaration Example</title>
</head>
<body>
<%
// Scriptlet tag: This code will be executed for each request
int currentValue = incrementCounter();
out.println("Declaration Counter Value: " + currentValue);
%>
</body>
</html>
In this example
- The variable counter is declared and initialized within a declaration tag.
- The method incrementCounter is defined to increment and return the counter value.
- A scriptlet tag calls the incrementCounter method and prints its value.
- The counter variable is preserved across requests, so its value increments with each request.
Summary of JSP Scriptlet tag and Declaration tag
Feature | Scriptlet Tag (<% %>) | Declaration Tag (<%! %>) |
Execution Timing | Executed each time the JSP page is requested | Executed when the servlet is initialized |
Code Placement | Inside _jspService method | Outside _jspService method, in the servlet class |
Use Case | Control flow, dynamic content generation | Variable and method declarations |