JSP Scripting Elements

JSP scripting allows you to insert Java code into Java Servlet generated from JSP page. These are the scripting elements: comment, expression, scriptlet, declaration and expression language.

JSP Comment

JSP comment is to document the code. In addition, JSP comment is used to note some parts of JSP page to make it clearer and easier to maintain. The following illustrates JSP comment inside a JSP page:

JSP comment is stripped off from the page in the response to the web browser.


The expression is one of the most basic scripting element in JSP. The expression is used to insert value directly to the output. The syntax of an expression is as follows:

It is noticed that there is no space between <% and =. For example, if you want to display the current date and time, you can use an expression as follows:

You can also use XML syntax of the JSP expression to achieve the same effect as the following example:


Scriptlet is similar to expression except for the equal sign “=”. You can insert any plain Java code inside a scriptlet. Because of mixing between Java code and HTML make JSP page difficult to maintain so scriptlet is not recommended for future development.
The following illustrates the syntax of scriptlet:

In this example, we display a greeting message based on the current time of the day using the scriptlet.

The XML syntax of JSP scriptlet is as follows:


If you want to define methods or fields, you can use JSP declaration. The JSP declaration is surrounded by the sign <%! and %>. For example, if you want to declare a variable x, you can use JSP declaration as follows:

The final semicolon is required.

The difference between a variable using declaration and a variable is declared using scriptlet is that a variable declared using declaration tag is accessible by all methods, while a variable declared using scriptlet is only accessible to the _jspservice() method of the generated servlet from the JSP page.

We can also declare a method using declaration tag as the following example:

  • Was this tutorial helpful ?
  • YesNo