JSP - Scripting Elements


This article is a series of JSP Tutorial. In this article, we will learn important JSP scripting elements with examples.

The scripting elements provide the ability to insert Java code inside the JSP.
In JSP, there are actually different types of scripting elements.
  1. JSP expressions
  2. JSP scriptlets
  3. JSP declarations
Now, we'll actually have a deep dive on each one of these topics in the separate article but I wanted to give you just an overview real quick.

Below diagram shows the summary of using these scripting elements:

Let's discuss each scripting element with their syntax and examples.

1. JSP expressions

We use JSP expressions to compute some type of expression and the result of that is included in the HTML page that's returned to the browser.
Expression tag evaluates the expression placed in it, converts the result into String and send the result back to the client through response implicit object.

The Syntax of JSP Expression Tag

<%= expression %>

JSP Expression Tag Examples

Here is sample snippet which basically converts this string to all caps or to all upper case.
<html>
   <body>
 Converting a string to uppercase:
 <%=new String("Hello World").toUpperCase()%>
   </body>
</html>

2. JSP scriptlets

A scriptlet is a set of Java programming statements embedded in an HTML page. The statements are distinguished from their surrounding HTML by being placed between <% and %> markers, as the following shows:
<% statement; [statement; …] %>

Example of JSP scriptlet tag

In this example, we are displaying a HelloWorld message.
```jsp
<html>  
   <body>  
       <% out.print("HelloWorld"); %>  
   </body>  
</html>  

3. JSP declarations

JSP declarations basically allow you to declare a method in the JSP page, and then you can call them from the same JSP page.
So it's very useful like any normal code that you create. If you need to execute some code over and over again, you simply encapsulate it in a method declaration.

The Syntax of JSP Declaration Tag

<%!  Declaration %>

JSP Declaration Tag Example

In this example of JSP declaration tag, we are defining the method which returns the cube of a given number and calling this method from the JSP expression tag. But we can also use JSP scriptlet tag to call the declared method.
<html>  
   <body>  
   <%!   
       int cube(int n){  
           return n * n * n;  
       }  
   %>  
   <%= "Cube of 3 is:"+cube(3) %>  
   </body>  
</html>  
Let's explore more about these scripting elements in upcoming articles. In the next article, we will learn JSP expression tag with an example.

Comments