JSP Scripting Elements

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

1. Declaration Tags.
2. Expression Tags.
3. Scriptles.

Declaration Tags: 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 Tags: 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>

Scriptlets: 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 :

<body>
  <%
    Date dob = new Date();
    out.println("Date of birth is "+dob);
    out.println("www.dineshonjava.com");
  %>
  </body>

Complete example here
index.jsp

<%@ page import="java.util.Date" %>
<html>  
    <body>
 <h1> Declaration  </h1>
 <%!
  int age = 25;
  String name = "Dinesh";
 %>
  <h1>Expression </h1>
 <%=name %>
 <%=age%>
 <h1>Scriptlets</h1>
    <%
  Date dob = new Date();
  out.println("Date of birth is "+dob);
  out.println("www.dineshonjava.com");
 %>
 </body>  
 </html>  

Copy the index.jsp file in to the webapp directory of tomcat.
C:Program Files (x86)Apache Software FoundationTomcat 7.0webappsindex

and start the server and hit the following url-
http://localhost:8080/index/index.jsp

 

<<Previous <<   || Index ||   >>Next >>
Previous
Next