0% found this document useful (0 votes)
1 views29 pages

Module IV

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views29 pages

Module IV

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Module IV JSP

JSP

2.1 Overview:

JSP stands for “Java server page” and built by SUN Microsystem.
JSP technology is used to create web application. It focuses more on presentation logic of the web
application. JSP pages are easier to maintain then a Servlet. JSP pages are opposite of Servlets.
Servlet adds HTML code inside Java code while JSP adds Java code inside HTML. Everything a
Servlet can do, a JSP page can also do it.
JSP enables us to write HTML pages containing tags that run powerful Java programs. JSP
separates presentation and business logic as Web designer can design and update JSP pages
without learning the Java language and Java Developer can also write code without concerning the
web design.

JSP Architecture:
The web server needs a JSP engine ie., container to process JSP pages. The JSP container is
responsible for intercepting requests for JSP pages. A JSP container works with the Web server to
provide the runtime environment and other services a JSP needs. It knows how to understand the
special elements that are part of JSPs.
Following diagram shows the position of JSP container and JSP files in a Web Application.

Fig: Architecture of jsp


JSP Processing:
1|Page
Module IV JSP

The following steps explain how the web server creates the web page using JSP:
i. User requesting a JSP page through internet via web browser.
ii. The JSP request is sent to the Web Server.
iii. Web server accepts the requested .jsp file and passes the JSP file to the JSP Servlet
Engine.
iv. If the JSP file has been called
» the first time then the JSP file is parsed
» otherwise servlet is instantiated.
v. The next step is to generate a servlet from the JSP file.
[In that servlet, all the HTML code is converted in println statements.]
vi. Now, the servlet source code file is compiled into a class file (bytecode file).
vii. The servlet is instantiated by calling the init and service methods of the servlet’s life
cycle.
v. Now, the generated servlet output is sent via the Internet form web server to user's
web browser.
vi. Now in last step, HTML results are displayed on the user's web browser.
In the end, a JSP is just a Servlet.
Life Cycle:
A JSP life cycle can be defined as the entire process from its creation till the destruction which is
similar to a servlet life cycle with an additional step which is required to compile a JSP into servlet.
The following are the paths
followed by a JSP
 Compilation
 Initialization
 Execution
 Cleanup

The four major phases of JSP life cycle are


very similar to Servlet Life Cycle and they
are as follows:

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

2|Page
Module IV JSP

JSP initialization:
When a container loads a JSP it invokes the jspInit() method which is identical in both Java Servlet
and applet. It is called first when the JSP is requested and is used to initialize objects and variables
that are used throughout the life of the JSP.
Syntax: public void jspInit(){
//Initialization code...
}

JSP execution:
Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine
invokes the _jspService() method is automatically and retrieves a connection to HTTP. It will call
doGet or doPost() method of servlet created.
Syntax:
void _jspService(HttpServletRequest request,
HttpServletResponse response) {
// Service handling code... }

JSP cleanup:
The jspDestroy() method is automatically called when the JSP terminates normally. Override
jspDestroy() for cleanup where resources used during the execution of the JSP, such as such as
releasing database connections or closing open files.
Syntax: public void jspDestroy{
// Initialization code...
}

All the above mentioned steps can be shown below in the following diagram:

Fig: Flow diagram of the JSP life Cycle


3|Page
Module IV JSP

JSP Operations in Various Scenarios:

2.2 Advantage of JSP over different technologies:

Advantage of JSP over Servlet:

Extension to Servlet:
JSP technology is the extension to servlet technology. We can use all the features of servlet
in JSP. In addition to, we can use implicit objects, predefined tags, expression language
and Custom tags in JSP that makes JSP development easy.

Easy to maintain
JSP can be easily managed because we can easily separate our business logic with
presentation logic. In servlet technology, we mix our business logic with the presentation
logic.

Fast Development: No need to recompile and redeploy


If JSP page is modified, we don't need to recompile and redeploy the project. The servlet
code needs to be updated and recompiled if we have to change the look and feel of the
application.

4|Page
Module IV JSP

Less code than Servlet


In JSP, we can use a lot of tags such as action tags, jstl, custom tags etc. that reduces the
code. Moreover, we can use EL, implicit objects etc.

Advantages of JSP vs. Active Server Pages (ASP):


First, the dynamic part is written in Java, not Visual Basic or other MS specific
language, so it is more powerful and easier to use.
Second, it is portable to other operating systems and non-Microsoft Web servers.

Advantages of JSP Vs PHP[“Hypertext Preprocessor”]:


First, is that the dynamic part is written in Java, which already has an extensive API for
networking, database access, distributed objects, and the like, whereas PHP requires
learning an entirely new, less widely used language.
A second, is that JSP is much more widely supported by tool and server vendors than is
PHP.

Advantages of JSP Vs. JavaScript:


JavaScript can generate HTML dynamically on the client but can hardly interact with the
web server to perform complex tasks like database access and image processing etc.

2.3 Basic syntax:


JSP tags are an important syntax element of Java Server Pages which start with "<%" and end
with "%>" just like HTML tags. Fundamental tags used in Java Server Pages are classified into
the following categories: -
 Comments
 Declaration tag
 Expression tag
 Scriptlet tag
 Directive tag
 Expression language tag

Tags Description Syntax


HTML content to be passed unchanged to
HTML Text <H1>Blah</H1>
the client
HTML HTML comment that is sent to the client <!- - Blah - ->
Comments but not displayed by the browser <! Blah >
Comments

Text sent unchanged to the client. HTML Anything


Template
text and HTML comments are just special <\% - - - - - %\>
Text
cases of this.
JSP Developer comment that is not sent to the <%- - Blah - -%>
Comment client <%! Blah %>

5|Page
Module IV JSP

is used within a Java Server page to declare <%! Field Definition; %>
a variable or method that can be referenced <%! Method Definition;%>
Types of Scripting Elements JSP by other declarations, scriptlets, or Eg:-
Declaration expressions in a java server page, when <%! int var = 1; %>
page is translated into a <%! int x, y ; %>
servlet.
Expression that is evaluated at requested <%= Java Value %>
JSP
time and sent to the client each time the Eg:-
Expression <%=new [Link]()%>
page is requested.
<% Java Statement %>
JSP Statement or statements that are executed Eg:-
Scriptlet each time the page is requested. <% [Link]("Your IP
address is " +
[Link]());%>
<%@ directive att="val" %>
page High-level information about the structure <%@page
JSP Directive

of the servlet code import="[Link].*"%>


code that is included at page-translation <%@ include
include: file="/[Link]" %>
time.
<%@ taglib
used to use the custom tags in the JSP
taglib: uri="tlds/[Link]"
pages. prefix="mytag" %>
JSP Expression The purpose of EL is to produce scriptless ${ EL Expression }
Language JSP pages.
<jsp:actionTag>
Action that takes place when the page is ..........
JSP Action requested </jsp:actionTag>
Table 2.1: Basic Syntax of JSP
Jsp Comments[Creating Template Text]:
JSP comment marks text or statements that the JSP container should ignore. A JSP comment
is useful when you want to hide or "comment out" part of your JSP page.
There are a special constructs you can use in various cases to insert comments or characters
that would otherwise be treated specially.
Syntax Purpose
<%-- comment --%> A JSP comment. Ignored by the JSP engine.
<!-- comment --> An HTML comment. Ignored by the browser.
<\% Represents static <% literal.
%\> Represents static %> literal.
\' A single quote in an attribute that uses single quotes.
\" A double quote in an attribute that uses double quotes.

6|Page
Module IV JSP

Example 1:
[Link]
<%--
Document : SimpleJsp
Created on : Mar 2, 2015, 5:09:35 AM
Author : Suma
--%>
<%@page contentType="text/html" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
<%-- This comment will not be visible in the page source --%>
<p><b> Creating Template text: </b>
<\% [Link]("Hello World"); \%><br>
</p>
</body>
</html>

Types of JSP Scripting Elements [invoking java code with JSP Scripting element]:
JSP scripting elements let you insert Java code into the servlet that will be generated from the
JSP page. There are three forms:
a. Expression Tag
b. Scriptlet Tag
c. Declaration Tag (For Definition refer table 2.1)

JSP Expressions
A JSP expression is used to insert values directly into the output. It has the following
form:

<%= Java Expression %>

The expression is evaluated, converted to a string, and inserted in the page. This
evaluation is performed at runtime (when the page is requested) and thus has full access
to information about the request. For example, the following shows the date/time that the
page was requested.
7|Page
Module IV JSP

Current time: <%= new [Link]() %>

Eg: [Link]
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>JSP Expressions</TITLE>
<META NAME="keywords" CONTENT="JSP,expressions,JavaServer Pages,servlets">
<META NAME="description" CONTENT="A quick example of JSP expressions.">
<LINK REL=STYLESHEETHREF="[Link]" TYPE="text/css">
</HEAD>
<BODY>
<H2>JSP Expressions</H2>
<UL>
<LI>Current time: <%= new [Link]() %>
<LI>Server: <%= [Link]() %>
<LI>Session ID: <%= [Link]() %>
<LI>The <CODE>testParam</CODE> form parameter:
<%= [Link]("testParam") %>
</UL>
</BODY>
</HTML>

Scriptlets Tag
If you want to do something more complex than output the value of a simple expression, JSP scriptlets
let you insert arbitrary code into the servlet’s _jspService method (which is called by service). Scriptlets
have the following form:

<% Java Code %>

Scriptlets have access to the same automatically defined variables as do expres- sions (request, response,
session, out, etc.). So, for example, if you want to explicitly send output to the resultant page, you could
use the out variable, as in the following example.

8|Page
Module IV JSP
<%
String queryData = [Link]();
[Link]("Attached GET data: " + queryData);
%>
Eg: [Link]
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Color Testing</TITLE>
</HEAD>
<%
String bgColor = [Link]("bgColor");
if ((bgColor == null) || ([Link]().equals(""))) { bgColor = "WHITE";
}%>
<BODY BGCOLOR="<%= bgColor %>">
<H2 ALIGN="CENTER">Testing a Background of "<%= bgColor %>"</H2>
</BODY></HTML>

Declaration tag

A JSP declaration lets you define methods or fields that get inserted into the main body of the servlet
class (outside the _jspService method that is called by service to process the request). A declaration has
the following form:

<%! Field or Method Definition %>

Eg: [Link]
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>

9|Page
Module IV JSP
<TITLE>JSP Declarations</TITLE>
<LINK REL=STYLESHEET HREF="[Link]" TYPE="text/css">
</HEAD>
<BODY>
<H1>JSP Declarations</H1>
<%! private int accessCount = 0; %>
<H2>Accesses to page since server reboot:
<%= ++accessCount %></H2>
</BODY></HTML>

Note: JSP expressions contain Java values and JSP scriptlets contain Java statements.

Controlling the Structure of generated servlets:

The JSP page directive:

JSP directives provide directions and instructions to the container, telling it how to handle
certain aspects of JSP processing.

A JSP directive affects the overall structure of the servlet class. It usually has the following form:

Syntax: i. <%@ directive attribute="value" %>

ii. <%@ directive attribute1="value1" attribute2="value2"


................
attributeN="valueN" %>

Note:
 Directives can have a number of attributes which you can list down as key-value pairs
and separated by commas.

 The blanks between the @ symbol and the directive name, and between the last attribute
and the closing %>, are optional.
10 | P a g e
Module IV JSP

 To obtain quotation marks within an attribute value, precede them with a backslash, using \’ for ’
and \" for ".

In JSP, there are three main types of directives:

i. <%@ page . . . %> Let’s you control the structure of the servlet by importing classes,
customizing the servlet superclass, setting the content type, and the
like.

ii. <%@ include . . . %> Let’s you insert a file into the JSP page at the time the JSP file is
translated into a servlet.

iii. <%@ taglib . . . %> defines custom markup tags.

i. The “page” directive:

The page directive is used to provide instructions to the container that pertain to the current
JSP page.

The page directive can define one or more of the following attributes and all are case-sensitive:

Sl.
Attributes Description
No.

i. import is used to define a set of class, interface or all the members of a package
that must be imported in servlet class definition
Syntax:

 <%@ page import = "[Link]" %>

 <%@ page import = "package.class1,... ,


[Link]" %>

Note: By default, the servlet imports following packages :


[Link].*; [Link].*; [Link].*; [Link].*;

For example: Refer Example-a

11 | P a g e
Module IV JSP

ii. contentType Defines the MIME (Multipurpose Internet Mail Extension) type of the
HTTP response.
Syntax:

 <%@ page contentType = “MIME Type" %>

 <%@ page contentType = “MIME Type”


charset = “Character - Set” %>

Note: By default value is "text/html; charset=ISO-8859-1".

For example: Refer Example-b

iii. pageEncoding is used to change the character set.


Syntax:

 <%@ page pageEncoding=" ISO-8859-1" %>


You can change this by specifying US-ASCII, Shift-JIS and etc.,

For example: Refer Example-b

iv. session Specifies whether or not the JSP page participates in HTTP sessions
Syntax:

 <%@ page session = “true" %>

 <%@ page session = “false” %>

12 | P a g e
Module IV JSP

It can have two values: true or false.


Default value is true: which means if you do not mention this attribute,
server may assume that HTTP session is required for this page.
For example: Refer Example-c

v. isELIgnored Specifies whether the JSP Expression Language (EL) is ignored (true)
or evaluated normally (false).
Syntax:
 <%@ page isELIgnored = “true" %>

 <%@ page isELIgnored = “false” %>


//By default false means EL is enabled

It can have two values: true or false.


Default value is false: which means Expression Language is enabled by
default.
For example: Refer Example-d

vi. buffer specifies the buffer size in kilobytes used by the out variable, which is
of type JspWriter.
Syntax:
 <%@ page buffer = “size kb" %>

 <%@ page buffer = “none” %>

Note:
Default size is 8Kb
Servers can use a larger buffer than you specify, but not a
smaller one.
For example: Refer Example-e

vii. autoFlush specifies whether the output buffer should be automatically flushed
when it is full (the default) or whether an exception should be raised
when the buffer overflows ( autoFlush="false").
Syntax:

 <%@ page autoFlush = “true" %>

 <%@ page autoFlush = “false” %>

13 | P a g e
Module IV JSP

It can have two values: true or false

Default value is true : which means automatically flushed when


buffered is full

For example: Refer Example-e

A value of false is illegal when buffer="none" as shown below:

 <%@ page buffer=“none” autoFlush=“false”


%>

viii. info defines a string that can be retrieved from the servlet by means of the
getServletInfo method.
Syntax:

 <%@ page info = “some message" %>

For example: Refer Example-f

ix. errorPage is used to define the error page, if exception occurs in the current page,
it will be redirected to the another JSP Page by the runtime.
Syntax:

 <%@ page errorPage = “RelativeURL” %>

The exception thrown will automatically be available to the designated


error page by means of the exception variable.

For example: Refer Example-g

x. iserrorPage indicates whether or not the current page can act as the error page for
another JSP page.
Syntax:

 <%@ page isErrorPage = “true” %>

 <%@ page isErrorPage = “false” %>

It can have two value: true or false

Default is false: which means not an error page.

For example: Refer Example-g

14 | P a g e
Module IV JSP

xi. isThreadSafe Servlet and JSP both are multithreaded. You can control that using
“isThreadSafe” atttribute.
Syntax:

 <%@ page isThreadSafe = “true” %>

 <%@ page isThreadSafe = “false” %>

The default value of isThreadSafe is true.

If you make it false, the web container will serialize the multiple requests,
i.e. it will wait until the JSP finishes responding to a request before
passing another request to it.

For Example: Refer Example-h

xii. language The “language’ attribute is intended to specify the scripting language
being used.
Syntax:

 <%@ page language = “java” %>


Default is java. But its support C++, PHP and other Scripting language
For Example: Refer Example-i

xiii. extends It specifies the superclass of the servlet that will be generated for the
JSP page.
Syntax:

 <%@ page extends= “[Link]” %>

For Example: Refer Example-i

15 | P a g e
Module IV JSP

Examples for the page directive attributes:


Example-a:

<%@page import="[Link]" contentType="text/html"


pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>Attributes demo</title>
</head>
<body>
<h1>Today Time is: <%= new Date() %></h1>
</body>
</html>

Output:

Example-b:

[Link]

package JavaPack;

public class Welcome {


public static String display()
{
return("Welcome");
}
}
[Link]
<%@page import="[Link],JavaPack.*"
contentType="application/msword"
pageEncoding="Shift-JIS"%>
<!DOCTYPE html>

16 | P a g e
Module IV JSP

[Link] [continued]

<!html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>Attributes demo</title>
</head>
<body>
<h1>Today Time is: <%= new Date() %></h1>
<%= [Link]()%>
</body>
</html>

Output:

Example-c:

[Link]
<%@page import="[Link],JavaPack.*"
contentType="text/html" pageEncoding="Shift-JIS"
session= "true"%>
<!DOCTYPE html>
<!html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>Attributes demo</title>
</head>
<body>
<h1>Today Time is: <%= new Date() %></h1>
<%= [Link]()%>
</body>
</html>

17 | P a g e
Module IV JSP

Output:

Example-d:

[Link]

<html>
<head>
<title>Expression Language</title>
</head>
<body>
<form action="[Link]">
Enter name: <input type="text" name="uname" /> <br><br>
<input type="submit" value="click here" />
</form>
</body>
</html>

[Link]

<%@page contentType="text/html" pageEncoding="UTF-8"


isELIgnored="true"%>
<!DOCTYPE html>
<html>
<body>
Welcome, ${[Link]}
</body>
</html>

18 | P a g e
Module IV JSP

Output:

if attribute value is true, then: ignored EL so output as shown below:

Example-e:

[Link]

<%@page import="[Link],JavaPack.*"
contentType="text/html"
pageEncoding="Shift-JIS"
session= "true"
buffer="16kb"
autoFlush="true"%>
<!DOCTYPE html>
<!html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>Attributes demo</title>
<link rel=STYLESHEET href="[Link]" type="text/css">
</head>
<body>
<h1>Today Time is: <%= new Date() %></h1>
<%= [Link]()%>
</body>
</html>

19 | P a g e
Module IV JSP
2
Example-f:
[Link]
<%@page import="[Link],JavaPack.*"
contentType="text/html"
pageEncoding="Shift-JIS"
info="Composed by Sonu Nigam"%>
<!DOCTYPE html>
<!html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>Attributes demo</title>
<link rel=STYLESHEET href="[Link]"
type="text/css">
</head>
<body>
<h1>Today Time is: <%= new Date() %></h1>
<%= [Link]()%>
</body>
</html>

Output:

Example-g:

[Link]

<%@page contentType="text/html" pageEncoding="UTF-8"


errorPage="[Link]"%>
<!DOCTYPE html>
<html>
<head>
<title>Error Page Demo</title>
</head>
<%! int a=0;%>
<body>
Result: <%= 100/a %>
</body>
</html>

20 | P a g e
Module IV JSP
2
[Link]

<%@page contentType="text/html" pageEncoding="UTF-8"


isErrorPage="true"%>
<!DOCTYPE html>
<html>
<head>
<title>Caught Error</title>
</head>
<body>
<h3>Sorry an exception occured!</h3><br/>
<h2>The exception is: <%= exception %> </h2>
</body>
</html>

Output: If A=2: If A=0:

Example-h:

[Link]

<%@page import="[Link],JavaPack.*"
contentType="text/html" pageEncoding=" UTF-8"
isThreadSafe="false"%>
<!DOCTYPE html>
<!html>
<head>
<title>Attributes demo</title>
<link rel=STYLESHEET href="[Link]" type="text/css">
</head>
<body>
<h1>Today Time is: <%= new Date() %></h1>
<%= [Link]()%>
</body>
</html>

21 | P a g e
Module IV JSP
2
Output:

Example-i:

<%@page import="[Link],JavaPack.*"
contentType="text/html"
pageEncoding="Shift-JIS"
language="java"
extends="[Link]"
%>
<!DOCTYPE html>
<!html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>Attributes demo</title>
<link rel=STYLESHEET href="[Link]" type="text/css">
</head>
<body>
<h1>Today Time is: <%= new Date() %></h1>
<%= [Link]()%>
</body>
</html>

XML Syntax for Directives:

If you are writing XML-compatible JSP pages follow the below syntax:

 <jsp:[Link] = “value” >


Example: <%@ page import="[Link].*" %>

XML equivalent as follows below:

<jsp:[Link] import="[Link].*" />

22 | P a g e
Module IV JSP
2
Implicit Objects:

Implicit
Description
Object
request The HttpServletRequest object associated with the request.
The HttpServletRequest object associated with the response that is sent
response
back to the browser.
out The JspWriter object associated with the output stream of the response.
The HttpSession object associated with the session for the given user of
session
request.
application The ServletContext object for the web application.

config The ServletConfig object associated with the servlet for current JSP page.

pageContext The PageContext object that encapsulates the enviroment of a singlerequest


for this current JSP page
page The page variable is equivalent to this variable of Java programming
language.
exception The exception object represents the Throwable object that was thrown by
some other JSP page.

• request

This variable is the HttpServletRequest associated with therequest; it gives you access to the request
parameters, the request type(e.g., GET or POST), and the incoming HTTP headers (e.g., cookies).

• response

This variable is the HttpServletResponse associated with the response to the client. Since the output
stream (see out) is normally buffered, it is usually legal to set HTTP status codes and response headers
in the body of JSP pages, even though the setting of headers or status codes is not permitted in servlets
once any output has been sent to the client.

• out

This variable is the Writer used to send output to the client. However, to make it easy to set response
headers at various places in the JSP page, out is not the standard PrintWriter but rather a buffered

23 | P a g e
Module IV JSP
2
version of Writer called JspWriter. You can adjust the buffer size through use of the buffer attribute
of the page directive. The out variable is used almost exclusively in scriptlets since JSP expressions
are automatically placed in the output stream and thus rarely need to refer to out explicitly.

• session

This variable is the HttpSession object associated with the request. Recall that sessions are created
automatically in JSP, so this variable is bound even if there is no incoming session reference. The one
exception is the use of the session attribute of the page directive to disable automatic session tracking.
In that case,attempts to reference the session variable cause errors at the timethe JSP page is translated
into a servlet.

• application

This variable is the ServletContext as obtained by getServletContext. Servlets and JSP pages can store
persistent data in the ServletContext object rather than in instance variables. ServletContext has
setAttribute and getAttribute methods that let you store arbitrary data associated with specified keys.
The difference between storing data in instance variables and storing it in the ServletContext is that the
ServletContext is shared by all servlets and JSP pages in the Web application, where as instance
variables are available only to the same servlet that stored the data.

• config

This variable is the ServletConfig object for this page. In principle, you can use it to read initialization
arameters, but, in practice, initialization parameters are read from jspInit, not from_jspService.

• pageContext

JSP introduced a class called PageContext to give a single point of access to many of the page attributes.
The PageContext class has methods getRequest, getResponse, getOut, getSession, and so forth. The
pageContext variable stores the value of the PageContext object associated with the current page. If a
method or constructor needs access to multiple page-related objects, passing pageContext is easier than
passing many separate references to request, response, out, and so forth.

• page
This variable is simply a synonym for this and is not very useful. It was created as a placeholder for the

24 | P a g e
Module IV JSP
time2when the scripting language could be something other than Java

JSP Action Tags:


There are many JSP action tags or elements. Each JSP action tag is used to perform some
specific tasks.

Action Tags Descriptions


forward forward the request to a new page
param Adds parameters to the request
include Includes a file at the time the page is requested
plugin Generates client browser-specific construct that makes an OBJECT or
EMBED tag for the Java Applets
element Defines XML elements dynamically
attribute defines dynamically defined XML element's attribute
fallback Supplies alternate text if java applet is unavailable on the client
body Used within standard or custom tags to supply the tag body.
text Use to write template text in JSP pages and documents.
getProperty retrieve a property from a JavaBean instance.
setProperty store data in JavaBeans instance.
useBean instantiates a JavaBean

Syntax:

<jsp:ActionTags Attribute= “names” >

<!- - Write any child tags- - >

</jsp:ActionTags>

i. forward action tag:

It is used to forward the request to another resource it may be jsp, html or another
resource.

Syntax:

25 | P a g e
Module IV JSP
2
Without Parameter
<jsp:forward page= “RelativeURL / <%= ExpressionTag %>” >
<!- - Write zero or more param tags- - >
</jsp:forward>

With Parameter
<jsp:forward page= “RelativeURL / <%= ExpressionTag %>” >
<jsp:param name=“paramname” value=“parmavalue”/>
</jsp:forward>

Example:

[Link]

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>This is [Link]</h1>
<jsp:forward page="[Link]">
<jsp:param name="user" value="suma"/>
</jsp:forward>
</body>
</html>

26 | P a g e
Module IV JSP
2

[Link]

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Print Date Page</h1>
Today date is <%= new [Link]()%> <br>
<%= [Link]("user")%>
</body>
</html>

Output:

ii. include action tag:


This tag is used to include the content of another resource it may be jsp, html or servlet
at request time.

Syntax:
Without Parameter

<jsp:include page= “RelativeURL / <%= ExpressionTag %>” >


<!- - Write zero or more param tags- - >
</jsp:include>

With Parameter

<jsp:include page= “RelativeURL / <%= ExpressionTag %>” >


<jsp:param name=“paramname” value=“parmavalue”/>
</jsp:include>
27 | P a g e
Module IV JSP
2
Example:

[Link]

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Demo on include action tag</h1>
<jsp:include page="[Link]">
<jsp:param name="user" value="suma"/>
</jsp:include>
</body>
</html>

[Link]

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Print Date Page</h1>
Today date is <%= new [Link]()%> <br>
<%= [Link]("user")%>
</body>
</html>
Output:

28 | P a g e
Module IV JSP
2

Questions
1. Explain lifecycle of JSP. (6M)
2. Explain the advantages of JSP over servlets.(6M)
3. Explain about JSP Expressions with example program.(8M)
4. Explain about JSP scriptlets with example program.(8M)
5. Explain about JSP Declarations with example program. (8M)
6. Discuss various types of JSP scripting elements .(12M)
7. Explain any 10 attributes of page directives with example. (10M)
8. Write a JSP program to implement all the attributes of page directive tag. (10M)
9. Explain the implicit objects of JSP. (8M)
10. Explain the following JSP action tags with example. (10M)
a) <jsp:forward> b) <jsp:include>

29 | P a g e

You might also like