JSP Scripting Elements with Example

In the previous tutorial, we have learned how a JSP Page translated into a servlet code. In this tutorial, we will learn about JSP Scripting Elements with Example. Basically, there are 3 types of Scripting Elements in JSP, JSP Declaration, JSP Scriplet, and JSP Expression tag. We will learn these tags in detail. But first, understand what is JSP Scripting Elements?

What are JSP Scripting Elements?

JSP Scripting elements are used to insert java codes into JSP pages. To manipulates the objects, and perform some computation on an object or runtime value, scripting elements are commonly used. There are three scripting elements types. These are the declaration, scriptlets, and expressions. The syntax starts with <% as follows:
                                      <%! this is a declaration %>
                                       <% this is a scriptlet %>  
                                       <%=  this is an expression %>

Read: How a JSP page translated into servlet code

JSP Declarations Tag:

Declaration tag in JSP Page is used to declare variable and methods. To define variables and methods of instance scope, it is used. Variable defined in declarations may be accessed from multiple threads, so they must be thread-safe. When JSP Page is initialized, then declaration is initialized and are made available to other declarations, scriptlets, and expressions.

Example of JSP Declaration Tag:

JSP Declaration Tag




JSP Declaration Tag




JSP Scriptlet Tag: 

Scriptlet tag is used to write java code into JSP Page. It is typical that scriptlets are intermingled with template text. Since each section has to be contained between the <% scriptlet code %> syntax, therefore this causes a  JSP page to be quite difficult to read. Because the variable and the code are local to the _jspService() method, therefore scriptlets don't have the same thread safety issue as declarations.


Example of JSP Scriptlet Tag:

JSP Scriptlet Tag


JSP Expression Tag: 

JSP Expression tag is used to print the value of variable and methods. At request processing time, the expression is evaluated, and then the result is converted into a String. If the result of the expression is an object, the toString() method is called. A ClassCastException will be raised if the value can't be coerced into a String at translation time.

If you don't know about Exceptions, we will be recommended you to first learn the basics of Exception in Java.

Example of JSP Expression Tag:

JSP Declaration Tag



JSP Scripting Elements with Example JSP Scripting Elements with Example Reviewed by Prashant Srivastava on November 08, 2018 Rating: 5

No comments:

Powered by Blogger.