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.
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:
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:
This directive should go to the start of JSP page.
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:
int i = 1, j=2;
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
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:
For example, you can reference a variable declared elsewhere within the file, like this:
Value from declaration: i + j =
i + j
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
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.