Module IV
Module IV
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.
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
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:
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.
4|Page
Module IV JSP
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
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:
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
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:
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:
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.
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:
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 ".
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.
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:
11 | P a g e
Module IV JSP
ii. contentType Defines the MIME (Multipurpose Internet Mail Extension) type of the
HTTP response.
Syntax:
iv. session Specifies whether or not the JSP page participates in HTTP sessions
Syntax:
12 | P a g e
Module IV JSP
v. isELIgnored Specifies whether the JSP Expression Language (EL) is ignored (true)
or evaluated normally (false).
Syntax:
<%@ page isELIgnored = “true" %>
vi. buffer specifies the buffer size in kilobytes used by the out variable, which is
of type JspWriter.
Syntax:
<%@ page buffer = “size kb" %>
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:
13 | P a g e
Module IV JSP
viii. info defines a string that can be retrieved from the servlet by means of the
getServletInfo method.
Syntax:
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:
x. iserrorPage indicates whether or not the current page can act as the error page for
another JSP page.
Syntax:
14 | P a g e
Module IV JSP
xi. isThreadSafe Servlet and JSP both are multithreaded. You can control that using
“isThreadSafe” atttribute.
Syntax:
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.
xii. language The “language’ attribute is intended to specify the scripting language
being used.
Syntax:
xiii. extends It specifies the superclass of the servlet that will be generated for the
JSP page.
Syntax:
15 | P a g e
Module IV JSP
Output:
Example-b:
[Link]
package JavaPack;
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]
18 | P a g e
Module IV JSP
Output:
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]
20 | P a g e
Module IV JSP
2
[Link]
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>
If you are writing XML-compatible JSP pages follow the below syntax:
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.
• 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
Syntax:
</jsp:ActionTags>
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]
26 | P a g e
Module IV JSP
2
[Link]
Output:
Syntax:
Without Parameter
With Parameter
[Link]
[Link]
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