In JSP, there are three types of Scripting elements -
JSP Scriplets
JSP Declarations
JSP Expressions
JSP Scriplets
Scriplets are used to embed Java code in your JSP page. The Java code is enclosed within tags <% %>, which are known as Scriplet Tags.
A JSP Scriplet tag may hold the Java code comprising java expressions, statements or variable. Let's see how -
A.jsp
<html>
<head>
<title>First JSP</title>
</head>
<body>
This is my first JSP page.
<%
int a=10, b=20;
int sum = a + b;
}
%>
</body>
</html>
Note: A JSP scriplet cannot hold method declaration.
JSP comes with a built-in Java
object named out which allows us to write a text to the JSP web page, Let's see how we can use the in-built out object within the scriplet tag to display a message on a web page.
A1.jsp
<html>
<head>
<title>JSP Scriplet Tag</title>
</head>
<body>
<% out.println("Saying hello from Java using Scriplet Tag"); %>
</body>
</html>
on executing this web page,
Note - The code in JSP Scriplets tag is automatically executed as soon as the JSP page loads.
Advertisement
JSP Declarations
In a JSP page, JSP declarations are only used to declare -
Java variables, or
Java methods
These variables and methods are part of a Java code within our JSP page and hence
they are accessible to the rest of Java code within other scriplet tags on the same webpage. We can declare java variables and methods within JSP Declaration tags such as -
<%! %>
Declaring a java variable in JSP webpage and using its value.
Note - The code in JSP Declaration tag is not automatically executed as soon as the JSP page loads, so this code has to be manually called for it to be executed.
Declaring java method in JSP web page.
A3.jsp
<html>
<head>
<title>JSP Declaration Tag</title>
</head>
<body>
<%! public void add()
{
int sum = 20 + 10;
}
%>
</body>
</html>
JSP Expressions
Java expressions result in a value, hence JSP Expression tags are used to enclose java expressions that yield a value to be printed on a JSP web page.
The Java expressions are enclosed in within <%= %> tags.
JSP expression which returns the value of a Java variable
Executing this JSP prints the value of java expression str which yields a value of String object.
JSP expression which returns the value from a Java method
A5.jsp
<html>
<head>
<title>JSP Declaration Tag</title>
</head>
<body>
<%! public int add(int a, int b)
{
int sum = a + b;
return sum;
}
%>
Sum of two integer is : <%= add(20,30) %>
</body>
</html>
Executing this JSP prints the value of java expression str which yields a value of String object.
Note
The Java expression in the JSP Expression tag should not end with a semicolon or it results in a error, hence in our example we have
called add() method in the Expression tag without ending it with a semicolon.