JSP Scripting Elements

Scripting elements are important part of JSP that makes page dynamic. Scripting elements can be classified in 3 categories:

1. Declaration Tag.
2. Expression Tag.
3. Scriptle Tag.

Declaration Tag: Declaration Tags is used to define variables and methods in JSP. Declaration Tags do not produce any output. Declaration Tag starts with <%! and ends with %>
Syntax.<%! datatype variable = value; %>

 

<body>
  <%!
  int age = 25;
  String name = "Dinesh";
  %>
  </body>

 

Expression Tag: Unlike Declaration Tags, Expression Tags produce output that can be used to display result on JSP. Expression Tag starts with <%= and ends with %>
Syntax- <%=variable %>
Examaple :
 

<body>
  <%=name %>
 <%=age%>
  </body>

 
 

Scriptlet Tag: Scriptlets are useful when you want to include JAVA code inside JSP. You may want to create a function that can be used to generate output based on different parameters passed at run time. In this case you may want to create JAVA function in Scriptlets and than call this function in Expression Tags at multiple location in JSP to display result on browser. Scriptlets starts with <% and ends with %>.
Syntax-<% out.println("www.dineshonjava.com") %>
Examaple :

  1. <body>
  2.   <%
  3.     Date dob = new Date();
  4.     out.println("Date of birth is "+dob);
  5.     out.println("www.dineshonjava.com");
  6.   %>
  7.   </body>


Complete example here
index.jsp

  1. <%@ page import="java.util.Date" %>
  2. <html>  
  3.     <body>
  4.  <h1> Declaration  </h1>
  5.  <%!
  6.   int age = 25;
  7.   String name = "Dinesh";
  8.  %>
  9.   <h1>Expression </h1>
  10.  <%=name %>
  11.  <%=age%>
  12.  <h1>Scriptlets</h1>
  13.     <%
  14.   Date dob = new Date();
  15.   out.println("Date of birth is "+dob);
  16.   out.println("www.dineshonjava.com");
  17.  %>
  18.  </body>  
  19.  </html>

 

Related Articles

post a comment