JSP Scriptlet

JSP Scriptlets allow JSP authors to include dynamic contents by using Java syntax within scriptlets. JSP allows Java code in between <% and %> constructs.

Using scriptlet allows JSP code to perform operations like iterations, applying conditional logic and to display values of elements from server side.

The simple example below illustrates how scriptlets are used to invoke Java code in JSP.

<html>
<body>
<% out.println(“Concatenation of 1 and 1 equals ” + 1 + 1 + ” where as addition of 1 and 1 equals ” + (1+1)); %>
</body>
</html>

This prints the following statement –

Concatenation of 1 and 1 equals 11 where as addition of 1 and 1 equals 2

The scriptlets have the following XML syntax –

<jsp:scriptlet> … </jsp:scriptlet>

Scriptlets can be used to iterate through a set of statements. This is done using the Java looping constructs. The example below prints ten Fibonocci numbers.

<html>
<body>
<table>
<% int j=1,k=1,temp; // Set j and k to 1.
for (int i=1; i <=10; i++) { // Iterate ten times.
%>
<tr>
<td><% out.println(i); %> </td>
<td><% temp=j; out.println(j);
j=j+k; // Set j to sum of last two numbers.
k=temp; // Set k to earlier value of j. %>
</td>
</tr>
<% } // Close the for loop here %>
</table>
</body>
</html>

The example above prints a table with first ten Fibonocci numbers. The output is shown below –

1 1
2 2
3 3
4 5
5 8
6 13
7 21
8 34
9 55
10 89

Lets say you now want to print alternate rows in the table with a yellow background. The powerful scripts comes to the rescue again. We can check for loop index using if statement. If loop index is even, the background color is set to yellow. The updated code is included below –

<html>
<body>
<table>
<% int j=1,k=1,temp; // Set j and k to 1.
for (int i=1; i <=10; i++) { // Iterate ten times.
%>
<tr>
<%
temp=j;
if ((i % 2) == 0) { %>
<td bgcolor=”yellow”><% out.println(i); %> </td>
<td bgcolor=”yellow”><% out.println(j); %> </td>
<% } else { %>
<td><% out.println(i); %> </td>
<td><% out.println(j); %> </td>
<% }
j=j+k; // Set j to sum of last two numbers.
k=temp; // Set k to earlier value of j. %>
%>
</tr>
<% } // Close the for loop here %>
</table>
</body>
</html>

The example above sets the background color to yellow for even rows. The output is shown below –

1 1
2 2
3 3
4 5
5 8
6 13
7 21
8 34
9 55
10 89




Share this:
Facebook Twitter Linkedin