Scriptlet - advanced
Now, let's put scriptlet to some interesting use.
This is how you do it. Start if block in scriptlet( line no. 5 ), then put some html code(line no. 7) and then close if block in another scriptlet ( line no. 9 ).
What the jsp engine (webserver) renders the jsp, it will put the enclosed html code (Good Morning!) in webpage only if the condition in if block (hourOfDay < 12) is true. Else the html code will be ignored.
This can be further extended to an else or elseif block with multiple scriptlets.
This is how you do it. Start if block in scriptlet( line no. 5 ), then put some html code(line no. 7) and then close if block in another scriptlet ( line no. 9 ).
What the jsp engine (webserver) renders the jsp, it will put the enclosed html code (Good Morning!) in webpage only if the condition in if block (hourOfDay < 12) is true. Else the html code will be ignored.
This can be further extended to an else or elseif block with multiple scriptlets.
<html> <body> <% int hourOfDay = new java.util.Date().getHours(); if (hourOfDay < 12) { %> Good Morning ! <!-- outside scriptlet--> <% } else { %> Good Day ! <!-- outside scriptlet--> <% } %> </body> </html>
Similarly, for loop and while loop can be split in multiple scriptlets to create dynamic web pages.
The only thing to take care of when using scriptlts thus is, all the scriptlets taken together should form syntactically correct java statements.
The only thing to take care of when using scriptlts thus is, all the scriptlets taken together should form syntactically correct java statements.
<html> <body> <% for(int i = 0; i < 10; i++) { %> <div> jsp scriptlets are awesome </div> <!-- outside scriptlet--> <% } %> </body> </html>
<html> <body> <% int i = 0; while (i++ < 5) { %> <div> jsp scriprlets awesome </div> <!-- outside scriptlet--> <% } %> </body> </html>