Introduction
By using servlets, the technology that controls the content and appearance of web pages is called JSP. JSP stands for Jakarta Server Pages, which helps create dynamically generated web pages based on HTML, XML, etc. Some small programs specified in the web pages run on the web server before sending to the user who requested it to modify the web pages.
Three types of Scripting elements in JSP are-
The scripting elements allow you to enter java code within the jsp. There is a total of three types of scripting elements in jsp.
Scriptlet tag
Scriptlet tags are the tags used to insert pure java code inside JSP, and Scriptlets in JSP are the java codes inserted inside <% and %> tags.
<html>
<head>
<title> JSP page: Welcome Ninjas!</title>
</head>
<body>
<%--Scriptlet example--%>
<%! String localstring= "Coding Ninjas"; %>
<%! String string2= "Coders"; %>
<%if(localstring.equals("Coding Ninjas")){%>
Hi </br>
<%}
else {%>
hello Ninjas
<%} %>
<%if(localstring.equals("JSP scriptlet Example"))
out.println("Hi"+string2);
else
out.println("Hello Ninjas");
%>
</body>
</html>
Output-
Expression tag
The code included within the JSP expression tag is sent to the response's output stream. As a result, you are not required to write anything. To write data, use print(). Its primary purpose is to print the values of variables or methods.
<html>
<body>
<%= "welcome to Coding Ninjas" %>
</body>
</html>
Output-
Declaration tag
For declaring fields and methods, we use the JSP declaration tag.
<html>
<body>
<%! int subscribers=5000; %>
<%= "Number of subscribers are "+ subscribers%>
</body>
</html>
Output-
Many JSP expression tag contains elements and the comment, Declaration element, etc., But now, we will focus on Scriptlets in JSP.
What are scriptlets tag?
Scriptlet tags are the tags used to insert pure java code inside JSP, and Scriptlets in JSP are the java codes inserted inside <% and %> tags.
Syntax-
<% java source code %>
How does it invoke?
The code inside the scriptlet tags is passed to _jspSrvice() by the JSP container while generating servlet from JSP. Every time the client requests _jspService() (JSP service method) gets invoked, the code inside the scriptlet tags executes every client's request.
Now we will come back o the example discussed above, and below mention are the Scriptlets in JSP statements which are being used in the above example -
<%if(localstring.equals("JSP scriptlet Example"))
out.println("Hi"+string2);
else
out.println("Hello Ninjas");
%>
If you notice in the above code that the code is in pure java language inside the tag, we use Scriptlets in JSP for executing the java code in JSP. We used Scriptlets in JSP for using if-else control flow statements of java.