Tutorial 3: JSP expressions and scriptlets

This tutorial will explain how to use both expressions and scriptlets to put dynamic content within your jsp pages.

Expressions:
Expressions provide the ability to include simple java within your page that is evaluated at run time with the result being output to the page. The character sequences <%= and %> to enclose Java expressions. Examples 1 and 2 from the source code below demonstrate this below.

1. Having an expression print the current date using java.util.Date()

Date:<%= new java.util.Date() %>2

2. Having an expression print “Hello World!” from a java String called helloWorld

<% String helloWorld = "Hello World!"; %>
<%= helloWorld %> <br>

Scriplets:
For more complicated java, scriptlets can be used. Scriplets provide more complicated blocks of java code to be inlucded within the page. Example 2 above shows a scriptlet created a local variable called helloWorld. Examples 4 and 5 demonstrate this further below.

3. Having an expression print true or false when comparing variables on the server side from a previous scriptlet code block.

<%
String result = "false";
int a = 1;
int b = 1; 
int c = 2;
if (a==b){
	result = "true";
}; 
%>

a(<%=a %>)==b(<%=b %>) = result<br>
result-> <%= result %> <br>

<% 
String result2 = "false";
if (a==c){
	result2 = "true";
}; %>

a(<%=a %>)==c(<%=c %>) = result2<br>
result2-> <%= result2 %> <br>

<br>

4. Using the out variable to have the scriplet generate HTML. (using out, the output will appear in the HTML page. In the below exampl, you should see “out – test” displayed in the html)

<% out.println("out - test"); %>

5. Using the System.out variable to have the scriptlet gerneate console outs. (using System.out, the output will appear within the eclipse console. In the below example, you should see “System.out – test appear in the eclipse console.” )

<% System.out.println("System.out - test"); %>

Leave a Reply

Your email address will not be published. Required fields are marked *