Hey guys in this article, you will learn about the JSP Scriptlet Syntax with easy to understand examples
Read More:
- Check the Complete JSP Tutorials
- Check the Complete Spring Boot Tutorials [100+ Examples]
- Check the Complete Spring Boot and Thymeleaf Tutorial
- Check the Complete AWS Tutorial
- Check the Complete JavaServer Faces (JSF) Tutorial
- Check the Complete Spring Data JPA Tutorial
- Check the Complete Spring Security Tutorial
- Check the Javascript Projects for Beginners
- Check the Spring Boot JdbcTemplate Tutorials
Table of Contents
Overview
- JSP Expressions allows us to include Java code inside the JSP file.
- JSP will process the Java code on the server and return the HTML content
- JSP Scriptlet allows us to insert 1 to many lines of java code
Element | Syntax |
JSP Expression | <%= //Java code %> |
JSP Scriptlet | <% //Java code %> |
JSP Declaration | <%! //Java code %> |
Examples
Following are some of the examples for JSP scriptlets
<%
out.println("2 + 3 = "+(2 + 3));
out.println("<br/>3 - 2 = "+(3 - 2));
out.println("<br/>2 * 3 = "+(2 * 3));
out.println("<br/>5 / 2 = "+(5 / 2));
%>
It produces the following output
2 + 3 = 5
3 - 2 = 1
2 * 3 = 6
5 / 2 = 2
We can include loops inside the scriptlets, consider the following example
<%
out.println("<br/>Even numbers are:");
for(int i = 0; i < 10; i++) {
if(i % 2 == 0) {
out.println("<br/>"+i);
}
}
%>
It produces the following output
Even numbers are:
0
2
4
6
8
Complete Example
Follow the below steps to understand the complete example
Create a Project
You can check the following post to create a new Dynamic We Project
Create a JSP file
Create JSPScriptlets.jsp
file under WebContent and add the following content
<%@page import="java.util.Date"%>
<%@ 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>
<%
out.println("<br/>Even numbers are:");
for(int i = 0; i < 10; i++) {
if(i % 2 == 0) {
out.println("<br/>"+i);
}
}
%>
</body>
</html>
Run the file
Right click on the File, choose Run As, choose Run on Server. It will open in a default web browser, you will see the following content
That’s it for this post, if you like this post, please share this post with your friends and collogues and also share this on your social media profiles.