JSP (JavaServer Pages) lets you combine HTML with Java to build dynamic web pages. One of the oldest ways to write Java code inside a JSP page is by using the Scriptlet Tag.
Although modern JSP applications often use Expression Language (EL) and JSTL instead of scriptlets, understanding them is still valuable for interviews, legacy projects, and learning how JSP works behind the scenes.
What is a JSP Scriptlet Tag?
A JSP Scriptlet Tag allows you to write executable Java code directly inside a JSP page. The code written inside a scriptlet runs whenever the page is requested by a client.
Syntax
<%
// Java code goes here
%>
The JSP engine places this code inside the generated servlet's _jspService() method, which means it executes for every request.
JSP Scripting Elements
JSP provides three scripting elements:
Scriptlet Tag – Executes Java statements.
Expression Tag – Prints values directly.
Declaration Tag – Declares fields and methods.
The scriptlet tag is specifically designed for writing Java logic inside a JSP page.
Example 1: Display a Welcome Message
<%
out.print("Welcome to JSP!");
%>
Output
Welcome to JSP!
Here, out is an implicit JSP object used to send output to the browser.
Example 2: Print User Input
You can also read values submitted from an HTML form.
index.html
welcome.jsp
<%
String name = request.getParameter("uname");
out.print("Welcome " + name);
%>
If the user enters John, the output will be:
Welcome John
Using Conditions in Scriptlets
Scriptlets can contain normal Java control statements.
<%
int age = 20;
if(age >= 18){
out.print("Adult");
}else{
out.print("Minor");
}
%>
Using Loops
You can generate HTML dynamically with loops.
<%
for(int i=1; i<=5; i++){
%>
<%
}
%>
| Number | <%= i %> |
This creates a table containing numbers from 1 to 5.
How Scriptlets Work
A JSP page is not executed directly. The server first converts it into a Java Servlet, compiles it, and then executes it. During this conversion, every scriptlet is placed inside the servlet's _jspService() method, so the code runs on each request.
Advantages
- Easy way to embed Java code in JSP.
- Useful for learning JSP internals.
- Helpful for understanding older JSP applications.
Limitations
Scriptlets are considered outdated because they mix Java code with HTML, making pages harder to maintain. Modern JSP development usually prefers:
- Expression Language (EL)
- JSTL (JSP Standard Tag Library)
- MVC frameworks such as Spring MVC
When Should You Learn Scriptlets?
Even though they're rarely used in new projects, scriptlets remain important for:
Java interview preparation
Maintaining legacy JSP applications
Understanding how JSP is translated into Servlets
Learn More
If you want a complete guide with additional examples of JSP Scriptlet Tags, visit TPointTech's JSP Scriptlet Tag Tutorial, where you'll find beginner-friendly explanations and practical examples to strengthen your JSP fundamentals.
Top comments (0)