Show TOC

Function documentationScripting Elements Locate this document in the navigation structure

 

You use JSP scripting elements to include Java code within a JSP.

Features

There are three types of scripting elements: expressions, scriptlets, and declarations.

Expressions

A JSP expression is a valid Java expression. Expressions are evaluated, the result is converted to a string and returned to the output. You can use expressions to pass request-time parameters and values to JSP actions. Expressions have the general syntax <%= expression %>.

Example Example

The following line inserts the current time:

  1. <%= new java.util.Date() %>
End of the code.

Caution Caution

JSP expressions do not require a closing semicolon, as they evaluate the result of a single expression.

End of the caution.
Scriptlets

A scriptlet is a block of Java code. Depending on the code, scriptlets may or may not generate output. All scriptlet code will be inserted into the _jspService() method of the generated servlet in the order in which scriptlets appear in the JSP. Scriptlets have the general syntax <% code %>.

Example Example

The following code prints a welcome message if a user object exists:

  1.     <%
          User user = (User)request.getAttribute("User");
          if (user != null) {
        %>
          Welcome, you have successfully logged in!
        <%
          }
        %>
    
End of the code.

Caution Caution

Variables declared in scriptlets are not available to the rest of the JSP, as they are local to the _jspService() method.

End of the caution.
Declarations

As with normal Java code, you can declare variables and methods. Declarations do not produce output to the out stream. They are initialized when the JSP is initialized and available to the rest of the page, that is, they are treated as global to the JSP. Any subsequent expressions, scriptlets, and declarations may use the variables and methods declared in this way. Declarations have the general syntax <%! code %>.

Example Example

The following line declares a variable of type integer and initializes it to zero:

End of the example.