Scripting Elements in JSP

There are three kinds of scripting elements available in JSP
  1. Declarations
  2. Scriptlets
  3. Expressions
Declarations:

Declarations are used to define methods & instance variables
  • Do not produce any output that is sent to client
  • Embedded in <%! and %> delimiters
The JSP declaration element defines page-scope variables to store information or defines supporting methods that the rest of a JSP page may need. Declaration elements do not produce outputs.

The declaration content must be a valid Java statement or multiple statements separated by semicolons. The contents of the declaration scripting element will be translated into Servlet Java code and inserted into the body of the translated corresponding Servlet code somewhere outside of any methods. 

Example:
<%! 
Public void jspDestroy() {
System.out.println(“JSP Destroyed”);
}
Public void jspInit() {
System.out.println(“JSP Loaded”);
}
int myVar = 123;
%>
The functions and variables defined are available to the JSP Page as well as to the servlet in which it is compiled

Scriptlets: 

  • Used to embed java code in JSP pages.
  • Contents of JSP go into _JSPpageservice() method
  • Code should comply with syntactical and semantic constuct of java
  • Embedded in <% and %> delimiters
Example:
<%
int x = 5;
int y = 7;
int z = x + y;
%>

The above scriptlet code inserted into the _jspService() method of the translated Servlet code which is invoked by the Servlet service() method. This java code is executed when the request is serviced by the JSP page. You can put any valid Java code within a scriptlet element, and it is not limited to one line of source code. 

Expressions:
  • Used to write dynamic content back to the browser.
  • If the output of expression is Java primitive the value is printed back to the browser
  • If the output is an object then the result of calling toString on the object is output to the browser
  • Embedded in <%= and %> delimiters
Example:
<%=“Java”+ “ “ + “Tech+ “ “ + “Info%> 
prints “Java Tech Info” to the browser
<%=new java.util.Date()%> 
prints date to the browser

Search:

Recent Posts