Quick Reference Study Notes for Java Server Pages (JSP) (Advanced)

Java Server Pages (JSP)

Introduction
Java Server Pages (JSP) is a server-side programming technology that enables creation of dynamic, platform-independent method for building Web-based applications.Java Server Page (JSP) is a technology for controlling the content or appearance of Web pages through the use of servlets, small programs that are specified in the Web page and run on the Web server to modify the Web page before it is sent to the user who requested it.

Following diagram shows the position of JSP container and JSP files in a Web application :

 

Features of JSP

Coding in JSP is easy :- As it is just adding JAVA code to HTML/XML.

Reduction in the length of Code :- In JSP we use action tags, custom tags etc.

Connection to Database is easier :-It is easier to connect website to database and allows to read or write data easily to the database.

Make Interactive websites :- In this we can create dynamic web pages which helps user to interact in real time environment.

Portable, Powerful, flexible and easy to maintain :- as these are browser and server independent.

No Redeployment and No Re-Compilation :- It is dynamic, secure and platform independent so no need to re-compilation.

JSP Architecture
Java Server Pages are part of a 3-tier architecture. A server(generally referred to as application or web server) supports the Java Server Pages. This server will act as a mediator between the client browser and a database. The following diagram shows the JSP architecture:

JSP Syntax

  1. Declaration Tag-It is used to declare the variables.

Syntax:- <%!  Dec var %>

  1. Java Scriplets- It allows us to add any number of JAVA code, variables and expressions.

Syntax:- <%!  Dec var %>

  1. Java Scriplets-It allows us to add any number of JAVA code, variables and expressions.

Syntax:- <% java code %>

  1. JSP Expression-It evaluates and convert the expression to a string.

Syntax:- <%= expression %>

  1. JAVA Comments-It contains the text that is added for information which has to be ignored.

Syntax:- <% -- JSP Comments %>

 

JSP Life Cycle

A JSP life cycle is defined as the process from its creation till the destruction. This is similar to a servlet life cycle with an additional step which is required to compile a JSP into servlet.

The four phases have been described below −

  1. 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 −

  1. Parsing the JSP.

  2. Turning the JSP into a servlet.

  3. Compiling the servlet.

 

  1. JSP Initialization

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.

  1. JSP Execution

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 _jspService() method takes an HttpServletRequest and an HttpServletResponse as its parameters as follows −

void _jspService(HttpServletRequest request, HttpServletResponse response) {

  // Service handling code… }

  1. JSP Cleanup

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.

The jspDestroy() method has the following form −

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

 

JSP Tag Library

The JavaServer Pages Standard Tag Library JSTL is a collection of useful JSP tags which

encapsulates core functionality common to many JSP applications.

The JSTL tags can be classified, according to their functions, into following JSTL tag library groups

that can be used when creating a JSP page:

  • Core Tags

  • Formatting tags

  • SQL tags

  • XML tags

  • JSTL Functions

 

Install JSTL Library:

If you are using Apache Tomcat container then follow the following two simple steps:

  1. Download binary distribution from Apache Standard Taglib and unpack compressed File.

      2.To use the Standard Taglib from its Jakarta Taglibs distribution, simply copy the JAR files in

the distribution's 'lib' directory to your application's webapps\ROOT\WEB-INF\lib directory.

To use any of the libraries, you must include a <taglib> directive at the top of each JSP that uses

the library.

Core Tags:

The core group of tags are the most frequently used JSTL tags. Following is the syntax to include

JSTL Core library in your JSP:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

There are following Core JSTL Tags:

 

<c:out >

Like <%= ... >, but for expressions.

<c:set >

Sets the result of an expression evaluation in a 'scope'

<c:remove >

Removes a scoped variable from a particular scope, if specified.

<c:catch>

Catches any Throwable that occurs in its body and optionally exposes it.

<c:if>

Simple conditional tag which evaluates its body if the supplied condition is true.

<c:choose>

Simple conditional tag that establishes a context for mutually exclusive conditional operations, marked by <when> and<otherwise>

<c:when>

Subtag of <choose> that includes its body if its condition evaluates to 'true'.

<c:otherwise>

Subtag of <choose> that follows <when> tags and runs only if all of the prior conditions evaluated to 'false'.

<c:redirect >

Redirects to a new URL.

<c:url>

Creates a URL with optional query parameters Formatting tags:

 

Formatting Tags:

The JSTL formatting tags are used to format and display text, the date, the time, and numbers for

internationalized Web sites. Following is the syntax to include Formatting library in your JSP:

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

Following is the list of Formatting JSTL Tags:

 

<fmt:formatNumber>

To render numerical value with specific precision or format.

<fmt:parseNumber>

Parses the string representation of a number, currency, or percentage.

<fmt:formatDate>

Formats a date and/or time using the supplied styles and pattern.

<fmt:parseDate>

Parses the string representation of a date and/or time.

<fmt:bundle>

Loads a resource bundle to be used by its tag body.

<fmt:setLocale>

Stores the given locale in the locale configuration variable.

<fmt:setBundle>

Loads a resource bundle and stores it in the named scoped variable or the bundle configuration variable.

<fmt:timeZone>

Specifies the time zone for any time formatting or parsing actions nested in its body.

<fmt:setTimeZone>

Stores the given time zone in the time zone configuration variable

<fmt:message>

To display an internationalized message.

<fmt:requestEncoding>

Sets the request character encoding

 

SQL tags:

The JSTL SQL tag library provides tags for interacting with relational databases RDBMSs such as

Oracle, mySQL, or Microsoft SQL Server.

Following is the syntax to include JSTL SQL library in your JSP:

<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>

Following is the list of SQL JSTL Tags:

 

<sql:setDataSource>

Creates a simple DataSource suitable only for prototyping

<sql:query>

Executes the SQL query defined in its body or through the sql attribute.

<sql:update>

Executes the SQL update defined in its body or through the sql attribute.

<sql:param>

Sets a parameter in an SQL statement to the specified value.

<sql:dateParam>

Sets a parameter in an SQL statement to the specified java.util.Date value.

<sql:transaction >

Provides nested database action elements with a shared Connection, set up to execute all statements as one transaction.

 

XML tags:

The JSTL XML tags provide a JSP-centric way of creating and manipulating XML documents.

Following is the syntax to include JSTL XML library in your JSP.

<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>

Following is the list of XML JSTL Tags:

 

<x:out>

Like <%= ... >, but for XPath expressions.

<x:parse>

Use to parse XML data specified either via an attribute or in the tag body.

<x:set >

Sets a variable to the value of an XPath expression.

<x:if >

Evaluates a test XPath expression and if it is true, it processes its body. If the test condition is false, the body is ignored.

<x:forEach>

To loop over nodes in an XML document.

<x:choose>

Simple conditional tag that establishes a context for mutually exclusive conditional operations, marked by <when> and <otherwise>

<x:when >

Subtag of <choose> that includes its body if its expression evaluates to 'true'.

<x:otherwise >

Subtag of <choose> that follows <when> tags and runs only if all of the prior conditions evaluated to 'false'.

<x:transform >

Applies an XSL transformation on a XML document

<x:param >

Use along with the transform tag to set a parameter in the XSLT stylesheet


 

JSTL Functions:

JSTL includes a number of standard functions, most of which are common string manipulation

functions. Following is the syntax to include JSTL Functions library in your JSP:

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

Following is the list of JSTL Functions:

 

fn:contains

Tests if an input string contains the specified substring.

fn:containsIgnoreCase

Tests if an input string contains the specified substring in a case insensitive way.

fn:endsWith

Tests if an input string ends with the specified suffix.

fn:escapeXml

Escapes characters that could be interpreted as XML markup.

fn:indexOf

Returns the index within a string of the first occurrence of a specified substring.

fn:join

Joins all elements of an array into a string.

fn:length

Returns the number of items in a collection, or the number of characters in a string.

fn:replace

Returns a string resulting from replacing in an input string all occurrences with a given string.

fn:split

Splits a string into an array of substrings.

fn:startsWith

Tests if an input string starts with the specified prefix.

fn:substring

Returns a subset of a string.

fn:substringAfter

Returns a subset of a string following a specific substring.

fn:substringBefore

Returns a subset of a string before a specific substring.

fn:toLowerCase

Converts all of the characters of a string to lowercase.

fn:toUpperCase

Converts all of the characters of a string to uppercase.

fn:trim

Removes white spaces from both ends of a string.


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