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

Java Server Pages (JSP) 2.x

Definition

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 −
<jsp:declaration>
  code fragment
</jsp:declaration>
 

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 −

<jsp:scriptlet>
  code fragment
</jsp:scriptlet>
 

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 }

 

Syntex-

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

$(expression) 

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 −

<jsp:text>
  <h1>Hello JSP!</h1>
</jsp:text>

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 −

<jsp:text>
   Box Perimeter is: ${2*box.width + 2*box.height}
</jsp:text>

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 −

S.No.

Operator & Description

1

. (Access a bean property or Map entry)

2

[] (Access an array or List element)

3

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

4

+ (Addition)

5

- (Subtraction or negation of a value)

6

* (Multiplication)

7

/ or div (Division)

8

% or mod (Modulo (remainder))

9

== or eq (Test for equality)

10

!= or ne (Test for inequality)

11

< or lt (Test for less than)

12

> or gt (Test for greater than)

13

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

14

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

15

&& or and (Test for logical AND)

16

|| or or (Test for logical OR)

17

! or not (Unary Boolean complement)

18

Empty (Test for empty variable values)

 

JSP EL Implicit Objects

The JSP expression language supports the following implicit objects −

S.No

Implicit object & Description

1

pageScope (Scoped variables from page scope)

2

requestScope (Scoped variables from request scope)

3

sessionScope (Scoped variables from session scope)

4

applicationScope (Scoped variables from application scope)

5

Param (Request parameters as strings)

6

paramValues (Request parameters as collections of strings)

7

Header (HTTP request headers as strings)

8

headerValues (HTTP request headers as collections of strings)

9

initParam (Context-initialization parameters)

10

Cookie (Cookie values)

11

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 −

${pageContext.request.queryString}
 

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 −

 

S.No.

Method Name

Description

1

getPropertyName()

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

2

setPropertyName()

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 −

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

*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