Quick Reference Study Notes for JSP 2.x (Foundation)

Java Server Pages (JSP) 2.x


JavaServer Pages (JSP) is a technology that facilitates the mixing of dynamic and static web contents. This helps developers insert java code in HTML pages by making use of special JSP tags, most of which start with <% and end with %>. You can write JSPs as text files that combine HTML or XHTML code, XML elements, and embedded JSP actions and commands.

Using JSP, you can collect input from users through Webpage forms, present records from a database or another source, and create Web pages dynamically. JSP tags can be used for a variety of purposes, such as retrieving information from a database or registering user preferences, accessing JavaBeans components, passing control between pages, and sharing information between requests, pages etc. JSP is meant to compliment Servlet, not a replacement. In a Model-View-Control (MVC) design, servlets are used for the controller, which involves complex programming logic. JSPs are used for the view, which deals with the presentation. The model could be implemented using JavaBeans or Enterprise JavaBeans (EJB) which may interface with a database.

JSP lifecycle

There are majorly four phases of a JSP life cycle which are very similar to the Servlet Life Cycle. These four phases have been described below −

  • JSP Compilation
    When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the page. If the page has never been compiled, or if the JSP has been modified since it was last compiled, the JSP engine compiles the page. The compilation process involves three steps −

    • Parsing the JSP.

    • Turning the JSP into a servlet.

    • Compiling the servlet.

  • JSP Initialization (jspInit())
    When a container loads a JSP it invokes the jspInit() method before servicing any requests. If you need to perform JSP-specific initialization, override the jspInit() method −

    public void jspInit() {
      // Initialization code...
    Typically, initialization is performed only once and as with the servlet init method, you generally initialize database connections, open files, and create lookup tables in the jspInit method.


  • JSP Execution (_jspService())
    This phase of the JSP life cycle represents all interactions with requests until the JSP is destroyed. Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine invokes the _jspService() method in the JSP. The method takes an HttpServletRequest and an HttpServletResponse as its parameters as follows −

    void _jspService(HttpServletRequest request, HttpServletResponse response) {
      // Service handling code...

The _jspService() method of a JSP is invoked on a request basis. This is responsible for generating the response for that request and this method is also responsible for generating responses to all seven of the HTTP methods, i.e, GET, POST, DELETE, etc.

  • JSP Cleanup (jspDestroy())
    The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a container. The jspDestroy() method is the JSP equivalent of the destroy method for servlets. Override jspDestroy when you need to perform any cleanup, such as releasing database connections or closing open files. The syntax for the method is below-

    public void jspDestroy() {
      // Your cleanup code goes here.

JSP Declaration

A declaration declares one or more variables or methods that you can use in Java code later in the JSP file. The code written inside the JSP declaration tag is placed outside the service() method of the auto-generated servlet. So it doesn't get memory at each request. You must declare the variable or method before you use it in the JSP file.

Following is the syntax for JSP Declarations −
<%! declaration; [ declaration; ]+ ... %>

You can write the XML equivalent of the above syntax as follows −
  code fragment

Following is an example for JSP Declarations −
<%! int j = 0; %>
<%! int x,y,z; %>
<%! Student student = new Student(“John”); %>

JSP Scriptlet
A scriptlet can contain any number of JAVA language statements, variable or method declarations, or expressions that are valid in the page scripting language. Any text, HTML tags, or JSP elements you write must be outside the scriptlet. JSP container moves statements in _jspservice() method while generating servlet from JSP. Following is the syntax of Scriptlet −

<% code fragment %>

You can write the XML equivalent of the above syntax as follows −

  code fragment

Following is an example for JSP Scriptlets −

<% int number1=10;

 int number2=40;

 int number3 = number1+number2;

 out.println("The count is-  " +number3);


Expression Language in JSP 2.0

The Expression Language (EL) has been introduced in JSP 2.0. The main purpose of this EL is to simplify the process of accessing the data from the bean properties and from the implicit objects. By using JSP Expression Language developers can get the data from JavaBeans, Maps, Arrays, and Lists that have been stored as attributes of a web application. SP Expression Language (EL) makes it possible to easily access application data stored in JavaBeans components. JSP EL allows you to create expressions both (a) arithmetic and (b) logical. Within a JSP EL expression, you can use integers, floating point numbers, strings, the built-in constants true and false for boolean values, and null. Some advantages of using Expression Language-


  • EL makes it easier to integrate the server-side state with the presentation output

  • EL expressions are no longer limited to the JSTL action attributes but may be used in any standard or custom action attribute declared to accept a runtime expression

  • EL expressions can be used in the static text and can directly be used in the template text outside of any actions

  • EL expressions are always written between the delimiters i.e. ${ and }



In a JSP, by default, the scripting elements are enabled and EL statement/expressions are disabled. To enable the EL expression in a JSP, developers need to use following page directive.

<%@ page isELIgnored="false"%>


EL Syntax


Here expr specifies the expression itself. The most common operators in JSP EL are .and []. These two operators allow you to access various attributes of Java Beans and built-in JSP objects. Typically, when you specify an attribute value in a JSP tag, you simply use a string. For example-

<jsp:setProperty name = "box" property = "perimeter" value = "100"/>

The above syntax <jsp:setProperty> tag can be written with an expression like −

<jsp:setProperty name = "box" property = "perimeter" value = "${2*box.width + 2*box.height}" />

 You can also use the JSP EL expressions within template text for a tag. For example, the <jsp:text> tag simply inserts its content within the body of a JSP. The following <jsp:text> declaration inserts <h1>Hello JSP!</h1> into the JSP output −

  <h1>Hello JSP!</h1>

You can now include a JSP EL expression in the body of a <jsp:text> tag (or any other tag) with the same ${} syntax you use for attributes. For example −

   Box Perimeter is: ${2*box.width + 2*box.height}

EL expressions can use parentheses to group subexpressions. For example, ${(1 + 2) * 3} equals 9, but ${1 + (2 * 3)} equals 7.

Basic Operators in EL

JSP Expression Language (EL) supports most of the arithmetic and logical operators supported by Java. Following table lists out the most frequently used operators −


Operator & Description


. (Access a bean property or Map entry)


[] (Access an array or List element)


( ) (Group a subexpression to change the evaluation order)


+ (Addition)


- (Subtraction or negation of a value)


* (Multiplication)


/ or div (Division)


% or mod (Modulo (remainder))


== or eq (Test for equality)


!= or ne (Test for inequality)


< or lt (Test for less than)


> or gt (Test for greater than)


<= or le (Test for less than or equal)


>= or ge (Test for greater than or equal)


&& or and (Test for logical AND)


|| or or (Test for logical OR)


! or not (Unary Boolean complement)


Empty (Test for empty variable values)


JSP EL Implicit Objects

The JSP expression language supports the following implicit objects −


Implicit object & Description


pageScope (Scoped variables from page scope)


requestScope (Scoped variables from request scope)


sessionScope (Scoped variables from session scope)


applicationScope (Scoped variables from application scope)


Param (Request parameters as strings)


paramValues (Request parameters as collections of strings)


Header (HTTP request headers as strings)


headerValues (HTTP request headers as collections of strings)


initParam (Context-initialization parameters)


Cookie (Cookie values)


pageContext (The JSP PageContext object for the current page)


The pageContext Object

The pageContext object gives you access to the pageContext JSP object. Through the pageContext object, you can access the request object. For example, to access the incoming query string for a request, you can use the following expression −


The Scope Objects

The pageScope, requestScope, sessionScope, and applicationScope variables provide access to variables stored at each scope level.

For example, if you need to explicitly access the box variable in the application scope, you can access it through the applicationScope variable as applicationScope.box.

 JSP - JavaBeans in 2.0

A JavaBean is a specially constructed Java class written in the Java and coded according to the JavaBeans API specifications.

Following are the unique characteristics that distinguish a JavaBean from other Java classes −

  • It provides a default, no-argument constructor.

  • It should be serializable and that which can implement the Serializable interface.

  • It may have a number of properties which can be read or written.

  • It may have a number of "getter" and "setter" methods for the properties.

JavaBeans Properties

A JavaBean property is a named attribute that can be accessed by the user of the object. The attribute can be of any Java data type, including the classes that you define.

A JavaBean property may be read, write, read-only, or write-only. JavaBean properties are accessed through two methods in the JavaBean's implementation class −



Method Name




For example, if property name is firstName, your method name would be getFirstName() to read that property. This method is called accessor.



For example, if property name is firstName, your method name would be setFirstName() to write that property. This method is called mutator.


Accessing JavaBeans

The useBean action declares a JavaBean for use in a JSP. Once declared, the bean becomes a scripting variable that can be accessed by both scripting elements and other custom tags used in the JSP. The full syntax for the useBean tag is as follows −

<jsp:useBean id = "bean's name" scope = "bean's scope" typeSpec/>
Here values for the scope attribute can be a page, request, session or application based on your requirement. The value of the id attribute may be any value as long as it is a unique name among other useBean declarations in the same JSP.

Following example shows how to use the useBean action −

     <title>useBean Example</title>
     <jsp:useBean id = "date" class = "java.util.Date" />
     <p>The date/time is <%= date %>

*NOTE : "This study material is collected from multiple sources to make a quick refresh course available to students."

This website uses cookies to improve user experience. By using our website you consent to all cookies in accordance with our Cookie Policy. More info. I Agree