JSP provides three types of scripting elements that allow you to embed Java code directly into HTML pages. Each serves a distinct purpose:
| Element | Syntax | Purpose |
|---|---|---|
| Scriptlet | <% code %> | Execute Java statements |
| Expression | <%= expr %> | Output a value to the page |
| Declaration | <%! decl %> | Declare variables/methods |
| JSP Comment | <%-- comment --%> | Server-side comment (not in HTML) |
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<body>
<%-- JSP Comment: Not visible in browser source --%>
<!-- HTML Comment: Visible in browser source -->
<h2>Scriptlet Example</h2>
<%
// Scriptlet: Java code block
int[] numbers = {1, 2, 3, 4, 5};
int sum = 0;
for (int n : numbers) {
sum += n;
out.println("<p>Number: " + n + "</p>");
}
%>
<p>Sum = <%= sum %></p>
<h2>Expression Example</h2>
<p>2 + 3 = <%= 2 + 3 %></p>
<p>String length: <%= "Hello World".length() %></p>
<p>Upper case: <%= "hello".toUpperCase() %></p>
</body>
</html>
Declarations (<%! %>) are used to declare instance variables and methods that belong to the generated Servlet class. Unlike scriptlets, declarations are placed outside the _jspService() method, so they are shared across all requests.
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%!
// Instance variable - shared across requests (be careful with thread safety!)
private int visitCount = 0;
// Method declaration
public String greet(String name) {
return "Hello, " + name + "! Welcome to JSP.";
}
// Factorial method
public long factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
%>
<html>
<body>
<%
visitCount++; // Increment visit counter
%>
<p>Visit count: <%= visitCount %></p>
<p><%= greet("Alice") %></p>
<p>5! = <%= factorial(5) %></p>
<p>10! = <%= factorial(10) %></p>
</body>
</html>
One of JSP's key features is the ability to mix HTML and Java code. You can open and close scriptlet tags multiple times, interleaving HTML between them:
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ page import="java.util.ArrayList, java.util.List"%>
<!DOCTYPE html>
<html>
<body>
<h2>Student List</h2>
<table border="1">
<tr><th>#</th><th>Name</th><th>Grade</th></tr>
<%
List<String[]> students = new ArrayList<>();
students.add(new String[]{"Alice", "A"});
students.add(new String[]{"Bob", "B+"});
students.add(new String[]{"Charlie", "A-"});
int i = 1;
for (String[] student : students) {
%>
<tr>
<td><%= i++ %></td>
<td><%= student[0] %></td>
<td><%= student[1] %></td>
</tr>
<%
} // end for loop
%>
</table>
</body>
</html>
Explore 500+ free tutorials across 20+ languages and frameworks.