JSP 2.0 specification defines expression language, which can be used by page authors to add dynamic behavior to their JSP pages. This language is rooted in XML and offers a familiar syntax to web developers without the need to develop deep into Java programming language.
The main feature of this language is that it can be easily extended by custom tag libraries. The language itself is quite simple and not very powerful, and only with custom tags (such as JSTL, Java Standard Tag Library) it shows its full potential. However, working with JSTL is out of the scope of this tutorial, so we will focus on basic expression language features. We will use JSP 2.0 XML syntax in all examples.
Scriptlets
A scriptlet is a piece of JSP code that can contain any valid Java code fragment. The syntax is similar to the following code sample:
<div>
Current time:
<jsp:scriptlet>
out.println(new Date());
</jsp:scriptlet>
</div>
Java code is inclosed in tags. Any valid Java code can be placed in scriptlet, but it is important to import any necessary classes used in a code. This is done in tag, as shown in the following snippet:
<jsp:directive.page import="java.util.Date"/>
This directive should go to the start of JSP page.
Declarations
JSP declarations declare one or more variables or methods that can be used in java code later in JSP file. The syntax for declaration is similar to the following:
<jsp:declaration>
int i = 1, j=2;
</jsp:declaration>
Any valid Java declaration can be enclosed within tags. Variables I and j can later be referenced in other parts of JSP page, as we will show in the next section
Expressions:
JSP expression element contains a scripting language expression, which is evaluated, converted to string and inserted into page where the expression element appears. Since the expression is converted into string, it can be used inline, even within HTML tags. Expression can be any valid Java expression, but it cannot be ended with a semicolon.
Expression syntax is as follows:
<jsp:expression>
expression
</jsp:expression>
For example, you can reference a variable declared elsewhere within the file, like this:
<div>
Value from declaration: i + j =
<jsp:expression>
i + j
</jsp:expression>
</div>
This is valid JSP expression which will print the sum of I and j variable we declared in the previous section. This would generate the following output:
Value from declaration: i + j = 3
Comments:
JSP comment marks text or statements that the JSP container should ignore. A JSP comment is useful when you want to hide or "comment out" part of your JSP page. Following is the syntax of JSP comments:
<%-- This is a comment --%>
The above line will be ignored by JSP engine and will not appear in HTML output of the final page.
You can download the sample web application here.