Scriptlets <%

What can be inserted into a JSP file?

First, Java code. If you want to insert Java code into your JSP, then the general format is given by the template:

 <%
	Java code
 %>

You can break this code into several parts:

 <%
   Beginning of Java Code
 %>
  HTML-code
<%
   End of Java Code
 %>

Example:


    <html> 
    <body> 
	<%
    	double num = Math.random();
    	if (num > 0.95) {
     %>
         <h2> You are lucky, user!</h2><p>(<%= num %>)</p>
 	<%
   	    } else {
     %> 
         <h2> Today is not your day, user!</h2><p>(<%= num %>)</p>
 	<%
   	    }
 	%>
  </body> 
   </html> 

Expression <%=

You can also insert any calculated expression into the JSP file. At the same time, the JSP parser itself will make sure that it is not only calculated, but also assigned where necessary. The expression inside the code is given by a template:

 <%= expression %>

Note that the semicolon is not needed here.

JSP servlet example with multiple expressions:

<p>root of 10 equals <%= Math.sqrt(10) %></p>
<h5><%= item[10] %></h5>
<p>current time: <%=  new java.util.Date() %></p>

This code will be converted to this Java code:

out.write("<p>");
out.write("The root of 10 is ");
out.print( Math.sqrt(10) );
out.write("</p>");
out.write("<h5>");
out.print( item[10] );
out.write("</h5>");
out.write("<p> Current time: ");
out.print( new java.util.Date()  );
out.write("</p>");

Important! In your Java code and expressions, you can use predefined variables such asrequest,response,session,outand so on.