JSP Scripting Elements:
In JSP we can write blocks of java code.You can do this by placing your Java code between <% and %> characters.This block of code is known as a "scripting element".Scripting element contains Java code that is executed every time the JSP is invoked.
Scripting elements can be classified in 3 categories:
- Declaration Tags.
- Expression Tags.
- Scriptles.
In JSP we can write blocks of java code.You can do this by placing your Java code between <% and %> characters.This block of code is known as a "scripting element".Scripting element contains Java code that is executed every time the JSP is invoked.
Scripting elements can be classified in 3 categories:
- Declaration Tags.
- Expression Tags.
- Scriptles.
Declaration Tags:
Declaration Tags is used to define variables and methods in JSP like java. Declaration Tag starts with <%! and ends with %>
The Code placed inside this tag must end with a semicolon (;).
For example, if you want to declare a variable x, ,you can use JSP declaration as follows:
<%! int x = 10; %>
The final semicolon is required.
We can also declare a method using declaration tag as given bellow:
<%! private int squre(int i) { i = i * i ; return i; } %>
Expression Tags :
Expression is one of the most basic scripting element in JSP. Expression is used to insert value directly to the output.
An expression tag contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file.
After the expression is evaluated the result is converted to a String and displayed.If any part of the expression is an Object,then the conversion is done using the toString() method of the Object.
Expression Tag starts with <%= and ends with %>
There should not be space between <% and =. For example, if you want to display the current date and time, you can use an expression as follows:
<%= new java.util.Date()%>
Scriptlets :
A scriptlet is a block of java code spec that is executed at run time. Scriptlets starts with <% and ends with %>.
Scriptlet is similar to expression except the equal sign “=”. You can insert any plain Java code inside a scriptlet.Following example display the current date and time.
<body> <% Date date = new Date(); out.println("Current Time is "+date); %> </body>
Complete Example containing all scriptlet Tags :
<body> <!-- Declaration Tag Example --> <%! int a = 15; String name = "Mukesh"; %> <!-- Expression Tag Example --> <%=name %> <!-- Scriptlet Example --> <% Date date = new Date(); out.println("Current Time is "+date); %> </body>
Related Articles