Expressions

Intertech Tutorials

Expressions

Scriptlets allow you to insert Java code into your HTML. Expressions are a simple way to output values to HTML. Below, an expression is added to hello.jsp to print out the value of i.


<html>
<body>
<%
for (int i =0; i < 10; i++) {
%>
<h1>Hello, JSP World</h1>
<%
}
%>
</body>
</html>
helloworld3-199x339

The expression starts with a <%= and ends with %> or <jsp:expression> and </jsp:expression>. The code put in an expression gets put inside of a write or print statement of the _jspService() method in generated servlet.


for (int i =0; i < 10; i++) {

out.write("\n");
out.write(" <h1>Hello, JSP World ");
out.print(i);
out.write("</h1>\n");
out.write(" ");
}

A common mistake is to add a semicolon (;) to an expression.


<h1>Hello, JSP World<%=i;%></h1>

The code above cannot be compiled by the JSP engine. An expression is not comprised of complete Java statement as scriptlets are. The compiler would try to take this statement and put it inside of a print statement resulting in the following syntactically incorrect code.


for (int i =0; i < 10; i++) {

out.write("\n");
out.write(" <h1>Hello, JSP World ");
out.print(i;);
out.write("</h1>\n");
out.write(" ");
}

Copyright (c) 2008-2013. Intertech, Inc. All Rights Reserved. This information is to be used exclusively as an online learning aid. Any attempts to copy, reproduce, or use for training is strictly prohibited.