0% found this document useful (0 votes)
11 views

Java Server Pages 416

JavaServer Pages (JSP) is a technology for creating dynamic web pages by embedding Java code within HTML, allowing for user input collection and database interaction. JSP pages are compiled into servlets and executed on a web server, with Apache Tomcat being the official reference implementation. The JSP lifecycle includes phases such as translation, compilation, and request processing, with lifecycle methods like jspInit(), _jspService(), and jspDestroy() managing the page's lifecycle.

Uploaded by

John Mulama
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Java Server Pages 416

JavaServer Pages (JSP) is a technology for creating dynamic web pages by embedding Java code within HTML, allowing for user input collection and database interaction. JSP pages are compiled into servlets and executed on a web server, with Apache Tomcat being the official reference implementation. The JSP lifecycle includes phases such as translation, compilation, and request processing, with lifecycle methods like jspInit(), _jspService(), and jspDestroy() managing the page's lifecycle.

Uploaded by

John Mulama
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

Java Server Pages

What is JavaServer Pages?


JavaServer Pages (JSP) is a technology for developing Webpages that supports dynamic content.
This helps developers insert java code in HTML pages by making use of special JSP tags, most of
which start with <% and end with %>.
A JavaServer Pages component is a type of Java servlet that is designed to fulfill the role of a user
interface for a Java web application. Web developers 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 Webpages 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.
Java Server Pages (JSP) is a technology that allows developers to create dynamic web pages using a
combination of HTML, XML, and Java code. JSP pages are executed on a web server, and the
resulting output is sent to the client's web browser. JSP provides a way to easily access Java code and
objects from within a web page, simplifying the creation of dynamic web pages. JSP pages are
typically used in conjunction with Java servlets, which handle data processing and client requests.
JSP is part of the Java EE platform and is supported by most web servers and servlet containers.

JSPs are Internally Compiled into Java Servlets

That is to say, anything that can be done using JSPs can also be accomplished using Java servlets.
However, it is important to note that servlets and JSPs are complementary technologies, NOT
replacement of each other. Servlet can be viewed as "HTML inside Java", which is better for
implementing business logic - as it is Java dominant. JSP, on the other hand, is "Java inside HTML",
which is superior for creating presentation - as it is HTML dominant. In a typical Model-View-
Control (MVC) application, servlets are often used for the Controller (C), which involves complex
programming logic. JSPs are often used for the View (V), which mainly deals with presentation. The
Model (M) is usually implemented using JavaBean or EJB.

Apache Tomcat Server

JSPs, like servlets, are server-side programs run inside a HTTP server. To support JSP/servlet, a
Java-capable HTTP server is required. Tomcat Server (@ http://tomcat.apache.org) is the official
reference implementation (RI) for Java servlet and JSP, provided free by Apache (@
http://www.apache.org) - an open-source software foundation.

 Life cycle of JSP Page

JSP life cycle is also managed by container. Usually every web container that contains servlet
container also contains JSP container for managing JSP pages. JSP pages life cycle phases are:

 Translation - JSP pages doesn’t look like normal java classes, actually JSP container parse
the JSP pages and translate them to generate corresponding servlet source code. If JSP file
name is home.jsp, usually its named as home_jsp.java.
 Compilation - If the translation is successful, then container compiles the generated servlet
source file to generate class file.
 Class Loading - Once JSP is compiled as servlet class, its lifecycle is similar to servlet and it
gets loaded into memory.

1
 Instance Creation - After JSP class is loaded into memory, its object is instantiated by the
container.
 Initialization - The JSP class is then initialized and it transforms from a normal class to
servlet. After initialization, ServletConfig and ServletContext objects become accessible to
JSP class.
 Request Processing - For every client request, a new thread is spawned with ServletRequest
and ServletResponse to process and generate the HTML response.
 Destroy - Last phase of JSP life cycle where it’s unloaded into memory.

 Life cycle methods of JSP

JSP lifecycle methods are:

1. jspInit() declared in JspPage interface. This method is called only once in JSP lifecycle to
initialize config params.
2. _jspService(HttpServletRequest request, HttpServletResponse response) declared in
HttpJspPage interface and response for handling client requests.
3. jspDestroy() declared in JspPage interface to unload the JSP from memory.

First JSP Example - "Java inside HTML"

Let's begin with a simple JSP example. We shall use the webapp called "hello" that we have created
in our earlier exercise. Use a programming text editor to enter the following HTML/JSP codes and
save as "first.jsp" (the file type of ".jsp" is mandatory) in your webapp (web context) home
directory (i.e., "webapps\hello".

1 <html>
2 <head><title>First JSP</title></head>
3 <body>
4 <%
5 double num = Math.random();
6 if (num > 0.95) {
7 %>
8 <h2>You'll have a luck day!</h2><p>(<%= num %>)</p>
9 <%
10 } else {
11 %>
12 <h2>Well, life goes on ... </h2><p>(<%= num %>)</p>
13 <%
14 }
15 %>
16 <a href="<%= request.getRequestURI() %>"><h3>Try Again</h3></a>
17 </body>
18 </html>

To execute the JSP script: Simply start your Tomcat server and use a browser to issue an URL to
browse the JSP page (i.e., http://localhost:8080/hello/first.jsp).

From your browser, choose the "View Source" option to check the response message. It should be
either of the followings depending on the random number generated.

<html>
<h2>You'll have a luck day!</h2>

2
<p>(0.987)</p>
<a href="first.jsp"><h3>Try Again</h3></a>
</html>
<html>
<h2> Well, life goes on ... </h2>
<p>(0.501)</p>
<a href="first.jsp"><h3>Try Again</h3></a>
</html>

It is important to note that the client is not able to "view" the original JSP script (otherwise, you may
have security exposure), but merely the result generated by the script.

Explanations

1. A JSP script is a regular HTML page containing Java programs. Recall that JSP is "Java
inside HTML" (whereas servlet is "HTML inside Java"). The Java statements are enclosed by
<% ... %> (called JSP scriptlet) or <%= ... %> (called JSP expression).
2. JSP Scriptlet <% ... %> is used to include Java statements.
3. JSP Expression <%= ... %> is used to evaluate a single Java expression and display its result.
4. The method request.getRequestURI() is used to retrieve the URL of the current page.
This is used in the anchor tag <a> for refreshing the page to obtain another random number.

Behind the Scene

When a JSP is first accessed, Tomcat converts the JSP into a servlet; compile the servlet, and execute
the servlet. Check out the generated servlet for "first.jsp", and study the JSP-to-servlet
conversion. Look under Tomcat's "work\Catalina\localhost\hello" for "first_jsp.java".

The relevant part of the generated servlet is extracted as follows (with some simplifications):

1 out.write("<html>\r\n ");
2 double num = Math.random();
3 if (num > 0.95) {
4 out.write("<h2>You will have a luck day!");
5 out.write("</h2><p>(");
6 out.print( num );
7 out.write(")</p>\r\n");
8 } else {
9 out.write("\r\n ");
10 out.write("<h2>Well, life goes on ... ");
11 out.write("</h2><p>(");
12 out.print( num );
13 out.write(")</p>\r\n ");
14 }
15 out.write("<a href=\"");
16 out.print( request.getRequestURI() );
17 out.write("\">");
18 out.write("<h3>Try Again</h3></a>\r\n");
19 out.write("</html>\r\n");

Explanation

1. The HTML statements are written out as part of the response via out.write(), as "it is".
2. The JSP scriptlets <% ... %> are kept, as "it is", in the converted servlet as the program logic.

3
3. The JSP expressions <%= ... %> are placed inside a out.print(). Hence, the expression
will be evaluated, and the result of the evaluation written out as part of the response message.

Compare the JSP script and the internally generated servlet, you shall understand that servlet is
"HTML inside Java", whereas JSP is "Java inside HTML".

Subsequent accesses to the same JSP will be much faster, because they will be re-directed to the
converted and compiled servlet directly (no JSP-to-servlet conversion and servlet compilation
needed again), unless the JSP has been modified.

JSPs are Internally Compiled into Java Servlets

That is to say, anything that can be done using JSPs can also be accomplished using Java servlets.
However, it is important to note that servlets and JSPs are complementary technologies, NOT
replacement of each other. Servlet can be viewed as "HTML inside Java", which is better for
implementing business logic - as it is Java dominant. JSP, on the other hand, is "Java inside HTML",
which is superior for creating presentation - as it is HTML dominant. In a typical Model-View-
Control (MVC) application, servlets are often used for the Controller (C), which involves complex
programming logic. JSPs are often used for the View (V), which mainly deals with presentation. The
Model (M) is usually implemented using JavaBean or EJB.

Apache Tomcat Server

JSPs, like servlets, are server-side programs run inside a HTTP server. To support JSP/servlet, a
Java-capable HTTP server is required. Tomcat Server (@ http://tomcat.apache.org) is the official
reference implementation (RI) for Java servlet and JSP, provided free by Apache (@
http://www.apache.org) - an open-source software foundation.

 Life cycle of JSP Page

JSP life cycle is also managed by container. Usually every web container that contains servlet
container also contains JSP container for managing JSP pages. JSP pages life cycle phases are:

 Translation - JSP pages doesn’t look like normal java classes, actually JSP container parse
the JSP pages and translate them to generate corresponding servlet source code. If JSP file
name is home.jsp, usually its named as home_jsp.java.
 Compilation - If the translation is successful, then container compiles the generated servlet
source file to generate class file.
 Class Loading - Once JSP is compiled as servlet class, its lifecycle is similar to servlet and it
gets loaded into memory.
 Instance Creation - After JSP class is loaded into memory, its object is instantiated by the
container.
 Initialization - The JSP class is then initialized and it transforms from a normal class to
servlet. After initialization, ServletConfig and ServletContext objects become accessible to
JSP class.
 Request Processing - For every client request, a new thread is spawned with ServletRequest
and ServletResponse to process and generate the HTML response.
 Destroy - Last phase of JSP life cycle where it’s unloaded into memory.

 Life cycle methods of JSP

4
JSP lifecycle methods are:

4. jspInit() declared in JspPage interface. This method is called only once in JSP lifecycle to
initialize config params.
5. _jspService(HttpServletRequest request, HttpServletResponse response) declared in
HttpJspPage interface and response for handling client requests.
6. jspDestroy() declared in JspPage interface to unload the JSP from memory.

First JSP Example - "Java inside HTML"

Let's begin with a simple JSP example. We shall use the webapp called "hello" that we have created
in our earlier exercise. Use a programming text editor to enter the following HTML/JSP codes and
save as "first.jsp" (the file type of ".jsp" is mandatory) in your webapp (web context) home
directory (i.e., "webapps\hello".

1 <html>
2 <head><title>First JSP</title></head>
3 <body>
4 <%
5 double num = Math.random();
6 if (num > 0.95) {
7 %>
8 <h2>You'll have a luck day!</h2><p>(<%= num %>)</p>
9 <%
10 } else {
11 %>
12 <h2>Well, life goes on ... </h2><p>(<%= num %>)</p>
13 <%
14 }
15 %>
16 <a href="<%= request.getRequestURI() %>"><h3>Try Again</h3></a>
17 </body>
18 </html>

To execute the JSP script: Simply start your Tomcat server and use a browser to issue an URL to
browse the JSP page (i.e., http://localhost:8080/hello/first.jsp).

From your browser, choose the "View Source" option to check the response message. It should be
either of the followings depending on the random number generated.

<html>
<h2>You'll have a luck day!</h2>
<p>(0.987)</p>
<a href="first.jsp"><h3>Try Again</h3></a>
</html>
<html>
<h2> Well, life goes on ... </h2>
<p>(0.501)</p>
<a href="first.jsp"><h3>Try Again</h3></a>
</html>

It is important to note that the client is not able to "view" the original JSP script (otherwise, you may
have security exposure), but merely the result generated by the script.

5
Explanations

5. A JSP script is a regular HTML page containing Java programs. Recall that JSP is "Java
inside HTML" (whereas servlet is "HTML inside Java"). The Java statements are enclosed by
<% ... %> (called JSP scriptlet) or <%= ... %> (called JSP expression).
6. JSP Scriptlet <% ... %> is used to include Java statements.
7. JSP Expression <%= ... %> is used to evaluate a single Java expression and display its result.
8. The method request.getRequestURI() is used to retrieve the URL of the current page.
This is used in the anchor tag <a> for refreshing the page to obtain another random number.

Behind the Scene

When a JSP is first accessed, Tomcat converts the JSP into a servlet; compile the servlet, and execute
the servlet. Check out the generated servlet for "first.jsp", and study the JSP-to-servlet
conversion. Look under Tomcat's "work\Catalina\localhost\hello" for "first_jsp.java".

The relevant part of the generated servlet is extracted as follows (with some simplifications):

1 out.write("<html>\r\n ");
2 double num = Math.random();
3 if (num > 0.95) {
4 out.write("<h2>You will have a luck day!");
5 out.write("</h2><p>(");
6 out.print( num );
7 out.write(")</p>\r\n");
8 } else {
9 out.write("\r\n ");
10 out.write("<h2>Well, life goes on ... ");
11 out.write("</h2><p>(");
12 out.print( num );
13 out.write(")</p>\r\n ");
14 }
15 out.write("<a href=\"");
16 out.print( request.getRequestURI() );
17 out.write("\">");
18 out.write("<h3>Try Again</h3></a>\r\n");
19 out.write("</html>\r\n");

Explanation

4. The HTML statements are written out as part of the response via out.write(), as "it is".
5. The JSP scriptlets <% ... %> are kept, as "it is", in the converted servlet as the program logic.
6. The JSP expressions <%= ... %> are placed inside a out.print(). Hence, the expression
will be evaluated, and the result of the evaluation written out as part of the response message.

Compare the JSP script and the internally generated servlet, you shall understand that servlet is
"HTML inside Java", whereas JSP is "Java inside HTML".

Subsequent accesses to the same JSP will be much faster, because they will be re-directed to the
converted and compiled servlet directly (no JSP-to-servlet conversion and servlet compilation
needed again), unless the JSP has been modified.

6
Facts About JSP
Here are some facts about JSP (JavaServer Pages):
 JSP stands for Java Server Pages.
 JSP is a technology to build dynamic web applications.
 JSP is a part of Java Enterprise Edition (Java EE).
 JSP is similar to HTML pages, but they also contain Java code executed on the server side.
 Server-side scripting means the JSP code is processed on the web server rather than the client
machine.
 A JSP page is a file with a ".jsp" extension that can contain a combination of HTML
Tags and JSP codes.
 To create a web page, JSP uses a combination of HTML or XML markup, JSP tags,
expressions, and Java code.
 JSP tags begin with <% and end with %>.
 JSP expressions are used to insert dynamic content into the page and begin with <%= and end
with %>.
 JSP can use JavaBeans to store and retrieve data.
 JSP requires a Java development environment and a Java Servlet Container such as Apache
Tomcat or Jetty.
 JSP is widely used in the industry for creating enterprise web applications.
 JSP is an improved extended version of Servlet technology.
Advantages of JSP
Some advantages of JSP (JavaServer Pages) include the following:
 JSP offers an efficient and more straightforward approach to coding dynamic web pages.
 JSP provides a wide variety of pre-built tags and custom tags, which can be used to add
functionality to web pages
 JSP allows developers to separate the presentation of the web page from the logic and
processing, making it easier to maintain the web application.
 Web Container (or application server like tomcat) handles changes when changes are done in
the JSP code and does not need recompilation.
 JSP allows developers to follow the Model-View-Controller (MVC) design pattern, which
separates a web application's presentation, logic, and data. This makes it easier to create
scalable and maintainable web applications.
 JSP is commonly used with other Java technologies, such as JavaServer Faces (JSF), which
provides a framework for building web applications, making the development process more
streamlined.
 Provides good security features like session tracking, user authentication, and access
restriction.
 JSP can use standard Java code and libraries, which increases the potential for code reuse.
Advantages of JSP than Servlet
JSP is considered to be better than servlet; there are many reasons why JSP is more beneficial than
servlet:
 JSP pages allow web designers to work with HTML or XML markup, while Servlets require
a deeper understanding of Java.
 JSP doesn't need additional files such as java class files, web.xml, etc.
 JSPs are compiled into servlets by the JSP engine, which improves performance compared to
interpreting servlets at runtime.
 Many IDEs and tools are available for developing JSPs, which can make development
quicker and easier compared to servlets.
 JSPs are more accessible to debug and troubleshoot than servlets because they have better
error reporting and debugging facilities.

7
Revisit Java Servlets

A typical Java servlet (as shown below) contains three kinds of methods: init(), destroy(), and
one or more service() methods such as doGet() and doPost(). init() runs when the servlet is
loaded. destroy() runs when the servlet is unloaded. service() runs once per HTTP request. The
service() methods takes two arguments: request and response, corresponding to the HTTP
request and response messages respectively. A PrintWriter called out is created for writing out the
response to the network.

Why Use JSP?


JavaServer Pages often serve the same purpose as programs implemented using the Common
Gateway Interface (CGI). But JSP offers several advantages in comparison with the CGI.
i. Performance is significantly better because JSP allows embedding Dynamic Elements in HTML
Pages itself instead of having separate CGI files.
ii. JSP are always compiled before they are processed by the server unlike CGI/Perl which requires
the server to load an interpreter and the target script each time the page is requested.
iii. JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP also has access
to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP, etc.
iv. JSP pages can be used in combination with servlets that handle the business logic, the model
supported by Java servlet template engines.

Finally, JSP is an integral part of Java EE, a complete platform for enterprise class applications. This
means that JSP can play a part in the simplest applications to the most complex and demanding.

Java server pages Architecture


The web server needs a JSP engine, i.e, a container to process JSP pages. The JSP container is
responsible for intercepting requests for JSP pages. This tutorial makes use of Apache which has
built-in JSP container to support JSP pages development.
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.

JSP Processing
The following steps explain how the web server creates the Webpage using JSP −

i. As with a normal page, your browser sends an HTTP request to the web server.

8
ii. The web server recognizes that the HTTP request is for a JSP page and forwards it to a JSP
engine. This is done by using the URL or JSP page which ends with .jsp instead of .html.
iii. The JSP engine loads the JSP page from disk and converts it into a servlet content. This
conversion is very simple in which all template text is converted to println( ) statements and all
JSP elements are converted to Java code. This code implements the corresponding dynamic
behavior of the page.
iv. The JSP engine compiles the servlet into an executable class and forwards the original request to
a servlet engine.
v. A part of the web server called the servlet engine loads the Servlet class and executes it. During
execution, the servlet produces an output in HTML format. The output is furthur passed on to
the web server by the servlet engine inside an HTTP respons
vi. The web server forwards the HTTP response to your browser in terms of static HTML content.
vii. Finally, the web browser handles the dynamically-generated HTML page inside the HTTP
response exactly as if it were a static page.

All the above mentioned steps can be seen in the following diagram −

Typically, the JSP engine checks to see whether a servlet for a JSP file already exists and whether
the modification date on the JSP is older than the servlet. If the JSP is older than its generated servlet,
the JSP container assumes that the JSP hasn't changed and that the generated servlet still matches the
JSP's contents. This makes the process more efficient than with the other scripting languages (such
as PHP) and therefore faster.
So in a way, a JSP page is really just another way to write a servlet without having to be a Java
programming wiz. Except for the translation phase, a JSP page is handled exactly like a regular
servlet.
In this chapter, we will discuss the lifecycle of JSP. The key to understanding the low-level
functionality of JSP is to understand the simple life cycle they follow.
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.

JSP and Java Servlets


Jakarta Server Pages (formerly JavaServer Pages) is a Java standard technology that developers use
to write dynamic, data-driven web pages for Java web applications. JSP is built on top of the Java
Servlet (aka Jakarta Servlet) specification and is one of the Java web technologies included for
ongoing support and upgrades in Jakarta EE.

JSP and servlets typically work together, especially in older Java web applications. From a coding
perspective, the most obvious difference between JSP and servlets is that with servlets you write Java

9
code and then embed client-side markup (like HTML) into that code. With JSP, you start with the
client-side script or markup, then embed JSP tags to connect your page to the Java back end.

Think of JSP as a way to write markup with ability to interact with the back end. Usually, markup
like HTML is sent to the client where it interacts with the back-end server via JavaScript. JSP pre-
processes the HTML with special commands to access and use server capabilities, then sends that
compiled page to the client.

Writing JSP pages

A simple JSP page consists of HTML markup embedded with JSP tags. JSP files have the .jsp
extension. The JSP server (also called a JSP container) is configured to direct an HTTP request to a
specific JSP page, which is then responsible for rendering an HTTP response.

When the request arrives, the file is processed on the server and the HTML is rendered as the
application view, a web page. The embedded JSP tags will be used to call server-side code and data.
The ultimate product of the JSP is vanilla HTML that the client browser can understand as-is. The
diagram in Figure 1 shows the interaction between HTML, JSP, and the web application server.

IDG
Figure 1. Overview of a Jakarta Server Pages (JSP) page in a web application.
Listing 1 shows a simple JSP page.

Listing 1. A simple JSP page

<html>

<body>

<p>${2 * 2} should equal 4</p>

</body></html>

Here, you see a block of HTML that includes a JSP expression, which is an instruction to the Java
server written using Expression Language (EL). In the expression ${2 * 2}, the ${} is JSP syntax for
interpolating code into HTML. The dollar sign with curly braces tells the JSP processor: “Hold on
for a second, we’re about to start talking about something special you need to take care of." When

10
executed, the JSP page will output the results of executing whatever is inside the expression. In this
case, the output will be the number 4.

Paths Followed By JSP


The following are the paths followed by a JSP −
 Compilation
 Initialization
 Execution
 Cleanup
The four major phases of a JSP life cycle are very similar to the Servlet Life Cycle. The 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
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
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) {

11
// Service handling code...}
The _jspService() method of a JSP is invoked on 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
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 jspDestroy() method has the following form −
public void jspDestroy() {
// Your cleanup code goes here.}
Elements of JSP
The elements of JSP have been described below −

JSP Scripting Elements

JSP provides the following scripting elements:

 JSP Comment <%-- comments -->


 JSP Expression <%= Java Expression %>
 JSP Scriptlet <% Java Statement(s) %>
 JSP Directive <%@ page|include ... %>
 JSP declarations

To simplify the access of the HTTP request and response messages, JSP has pre-defined the
following variables:

 request: corresponds to the HTTP request message.


 response: corresponds to the HTTP response message.
 out: corresponds to the HTTP response message’s output stream.
 others such as session, page, application, pageContext, which are outside of this tutorial.

1. JSP comment <%-- comments --%>

JSP comments <%-- comments --%> are ignored by the JSP engine. For example,

<%-- anything but a closing tag here will be ignored -->


JSP Comments
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", a part of your JSP page.
Following is the syntax of the JSP comments −
<%-- This is JSP comment --%>
Following example shows the JSP Comments −
<html>
<head><title>A Comment Test</title></head>

<body>

12
<h2>A Test of Comments</h2>
<%-- This comment will not be visible in the page source --%>
</body> </html>
The above code will generate the following result −
A Test of Comments

There are a small number of special constructs you can use in various cases to insert comments or
characters that would otherwise be treated specially. Here's a summary −
S.No. Syntax & Purpose

<%-- comment --%>


1
A JSP comment. Ignored by the JSP engine.

<!-- comment -->


2
An HTML comment. Ignored by the browser.

<\%
3
Represents static <% literal.

%\>
4
Represents static %> literal.

\'
5
A single quote in an attribute that uses single quotes.

\"
6
A double quote in an attribute that uses double quotes.

Note that HTML comment is <!-- comments -->. JSP expression within the HTML comment will
be evaluated. For example,

<!-- HTML comments here <%= Math.random() %> more comments -->

2. JSP Scriptlet <% Java statement(s) %>

JSP scriptlets allow you to do more complex operations than inserting a single Java expression (with
the JSP expression). JSP scriptlets let you insert an arbitrary sequence of valid Java statement(s) into
the service() method of the converted servlet. All the Java statements in a scriptlet are to be
terminated with a semi-colon. A scriptlet can contain any number of JAVA language statements,
variable or method declarations, or expressions that are valid in the page scripting language.

Following is the syntax of Scriptlet −


<% code fragment %>
You can write the XML equivalent of the above syntax as follows −
<jsp:scriptlet>
code fragment

13
</jsp:scriptlet>
Any text, HTML tags, or JSP elements you write must be outside the scriptlet. Following is the
simple and first example for JSP −
<html>
<head><title>Hello World</title></head>

<body>
Hello World!<br/>
<%
out.println("Your IP address is " + request.getRemoteAddr());
%>
</body></html>
NOTE − Assuming that Apache Tomcat is installed in C:\apache-tomcat-7.0.2 and your
environment is setup as per environment setup tutorial.
Let us keep the above code in JSP file hello.jsp and put this file in C:\apache-
tomcat7.0.2\webapps\ROOT directory. Browse through the same using
URL http://localhost:8080/hello.jsp. The above code will generate the following result −

Example2:

<%
String author = request.getParameter("author");
if (author != null && !author.equals(""))) {
%>
<p>You have choose author <%= author %></p>
<%
}
%>

In the converted servlet, the above will be inserted into the service() method as follows:

String author = request.getParameter("author");


if (author != null && !author.equals(""))) {
out.write("<p>You have choose author ");
out.print( author );
out.write("</p>");
}

Notice that the Java codes inside a scriptlet are inserted exactly as they are written, and used as the
programming logic. The HTML codes are passed to an out.write() method and written out as part
of the response message.

14
3.JSP Declarations
A declaration declares one or more variables or methods that you can use in Java code later in the
JSP file. 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 i = 0; %>
<%! int a, b, c; %>
<%! Circle a = new Circle(2.0); %>

JSP Expression <%= Java Expression %>

A JSP expression element contains a scripting language expression that is evaluated, converted to a
String, and inserted where the expression appears in the JSP file.
Because the value of an expression is converted to a String, you can use an expression within a line
of text, whether or not it is tagged with HTML, in a JSP file.
The expression element can contain any expression that is valid according to the Java Language
Specification but you cannot use a semicolon to end an expression.
Following is the syntax of JSP Expression −
<%= expression %>

JSP Expression can be used to insert a single Java expression directly into the response
message. This expression will be placed inside a out.print() method. Hence, the expression will
be evaluated and printed out as part of the response message. Any valid Java expression can be
used. There is no semi-colon at the end of the expression. For examples:

<p>The square root of 5 is <%= Math.sqrt(5) %></p>


<h5><%= item[10] %></h5>
<p>Current time is: <%= new java.util.Date() %></p>

The above JSP expressions will be converted to:

out.write("<p>The square root of 5 is ");


out.print( Math.sqrt(5) );
out.write("</p>");
out.write("<h5>");
out.print( item[10] );
out.write("</h5>");
out.write("<p>Current time is: ");
out.print( new java.util.Date() );
out.write("</p>");

You can use the pre-defined variables, such as request, in the expressions. For examples:

<p>You have choose author <%= request.getParameter("author") %></p>


<%= request.getRequestURI() %>
<%= request.getHeader("Host") %>

15
You can write the XML equivalent of the above syntax as follows −
<jsp:expression>
expression</jsp:expression>
Following example shows a JSP Expression −
<html>
<head><title>A Comment Test</title></head>

<body>
<p>Today's date: <%= (new java.util.Date()).toLocaleString()%></p>
</body> </html>
The above code will generate the following result −
Today's date: 11-Sep-2010 21:24:25

4.JSP Directive <%@ page|include ... %>

Directives supply directions and messages to a JSP container. The directives provide global
information about the entire page of JSP. Hence, they are an essential part of the JSP code. These
special instructions are used for translating JSP to servlet code. In this chapter, you will learn about
the different components of directives in detail.In JSP's life cycle phase, the code must be converted
to a servlet that deals with the translation phase. They provide commands or directions to the
container on how to deal with and manage certain JSP processing portions. Directives can contain
several attributes that are separated by a comma and act as key-value pairs. In JSP, directives are
described with a pair of <%@ .... %> tags.

The syntax of Directives looks like:

<%@ directive attribute="" %>

JSP directives provide instructions to the JSP engine. The syntax of the JSP directive is:

<%@ directive_name
attribute1="value1"
attribute2="value2"
......
attributeN="valueN" %>

JSP page Directive

The "page" directive lets you import classes and customize the page properties. For examples,

<%-- import package java.sql.* -->


<%@ page import="java.sql.*" %>

<%-- Set the output MIME type -->


<%@ page contentType="image/gif" %>

<%-- Set an information message for getServletInfo() method -->


<%@ page info="Hello-world example" %>

16
JSP include Directive

The "include" directive lets you include another file(s) at the time when the JSP page is compiled
into a servlet. You can include any JSP files, or static HTML files. You can use include directive to
include navigation bar, copyright statement, logo, etc. on every JSP pages. The syntax is:

<%@ include file="url" %>

For example:

<%@ include file="header.html" %>


......
<%@ include file="footer.html" %>

A JSP directive affects the overall structure of the servlet class. It usually has the following form −
<%@ directive attribute="value" %>
There are three types of directive tag −
S.No. Directive & Description

<%@ page ... %>


1 Defines page-dependent attributes, such as scripting language, error page, and
buffering requirements.

<%@ include ... %>


2
Includes a file during the translation phase.

<%@ taglib ... %>


3
Declares a tag library, containing custom actions, used in the page
We would explain the JSP directive in a separate chapter JSP - Directives
JSP Actions
JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can
dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate
HTML for the Java plugin.
There is only one syntax for the Action element, as it conforms to the XML standard −
<jsp:action_name attribute="value" />
Action elements are basically predefined functions. Following table lists out the available JSP
Actions −
S.No. Syntax & Purpose

jsp:include
1
Includes a file at the time the page is requested.

jsp:useBean
2
Finds or instantiates a JavaBean.

3 jsp:setProperty

17
Sets the property of a JavaBean.

jsp:getProperty
4
Inserts the property of a JavaBean into the output.

jsp:forward
5
Forwards the requester to a new page.

jsp:plugin
6 Generates browser-specific code that makes an OBJECT or EMBED tag for the Java
plugin.

jsp:element
7
Defines XML elements dynamically.

jsp:attribute
8
Defines dynamically-defined XML element's attribute.

jsp:body
9
Defines dynamically-defined XML element's body.

jsp:text
10
Used to write template text in JSP pages and documents.
We would explain JSP actions in a separate chapter JSP - Actions
JSP Implicit Objects
JSP supports nine automatically defined variables, which are also called implicit objects. These
variables are −
S.No. Object & Description

request
1
This is the HttpServletRequest object associated with the request.

response
2
This is the HttpServletResponse object associated with the response to the client.

out
3
This is the PrintWriter object used to send output to the client.

session
4
This is the HttpSession object associated with the request.

application
5
This is the ServletContext object associated with the application context.

config
6
This is the ServletConfig object associated with the page.

18
pageContext
7 This encapsulates use of server-specific features like higher
performance JspWriters.

page
8 This is simply a synonym for this, and is used to call the methods defined by the
translated servlet class.

Exception
9
The Exception object allows the exception data to be accessed by designated JSP.
We would explain JSP Implicit Objects in a separate chapter JSP - Implicit Objects.
Control-Flow Statements
You can use all the APIs and building blocks of Java in your JSP programming including decision-
making statements, loops, etc.
Decision-Making Statements
The if...else block starts out like an ordinary Scriptlet, but the Scriptlet is closed at each line with
HTML text included between the Scriptlet tags.
<%! int day = 3; %> <html>
<head><title>IF...ELSE Example</title></head>

<body>
<% if (day == 1 || day == 7) { %>
<p> Today is weekend</p>
<% } else { %>
<p> Today is not weekend</p>
<% } %>
</body> </html>
The above code will generate the following result −
Today is not weekend
Now look at the following switch...case block which has been written a bit differentlty
using out.println() and inside Scriptletas −
<%! int day = 3; %> <html>
<head><title>SWITCH...CASE Example</title></head>

<body>
<%
switch(day) {
case 0:
out.println("It\'s Sunday.");
break;
case 1:
out.println("It\'s Monday.");
break;
case 2:
out.println("It\'s Tuesday.");
break;
case 3:
out.println("It\'s Wednesday.");

19
break;
case 4:
out.println("It\'s Thursday.");
break;
case 5:
out.println("It\'s Friday.");
break;
default:
out.println("It's Saturday.");
}
%>
</body> </html>
The above code will generate the following result −
It's Wednesday.

Loop Statements
You can also use three basic types of looping blocks in Java: for, while, and do…while blocks in
your JSP programming.
Let us look at the following for loop example −
<%! int fontSize; %> <html>
<head><title>FOR LOOP Example</title></head>

<body>
<%for ( fontSize = 1; fontSize <= 3; fontSize++){ %>
<font color = "green" size = "<%= fontSize %>">
JSP Tutorial
</font><br />
<%}%>
</body> </html>
Above example can be written using the while loop as follows −
<%! int fontSize; %> <html>
<head><title>WHILE LOOP Example</title></head>

<body>
<%while ( fontSize <= 3){ %>
<font color = "green" size = "<%= fontSize %>">
JSP Tutorial
</font><br />
<%fontSize++;%>
<%}%>
</body> </html>
The above code will generate the following result −
JSP Operators
JSP supports all the logical and arithmetic operators supported by Java. Following table lists out all
the operators with the highest precedence appear at the top of the table, those with the lowest appear
at the bottom.

JSP ACTIONS

20
These actions use constructs in XML syntax to control the behavior of the servlet engine. You can
dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate
HTML for the Java plugin.
There is only one syntax for the Action element, as it conforms to the XML standard −
<jsp:action_name attribute = "value" />
Action elements are basically predefined functions. The following table lists out the available JSP
actions −
S.No. Syntax & Purpose

jsp:include
1
Includes a file at the time the page is requested.

jsp:useBean
2
Finds or instantiates a JavaBean.

jsp:setProperty
3
Sets the property of a JavaBean.

jsp:getProperty
4
Inserts the property of a JavaBean into the output.

jsp:forward
5
Forwards the requester to a new page.

jsp:plugin
6 Generates browser-specific code that makes an OBJECT or EMBED tag for the Java
plugin.

jsp:element
7
Defines XML elements dynamically.

jsp:attribute
8
Defines dynamically-defined XML element's attribute.

jsp:body
9
Defines dynamically-defined XML element's body.

jsp:text
10
Used to write template text in JSP pages and documents.
Common Attributes
There are two attributes that are common to all Action elements: the id attribute and
the scope attribute.
Id attribute
The id attribute uniquely identifies the Action element, and allows the action to be referenced inside
the JSP page. If the Action creates an instance of an object, the id value can be used to reference it
through the implicit object PageContext.
Scope attribute

21
This attribute identifies the lifecycle of the Action element. The id attribute and the scope attribute
are directly related, as the scope attribute determines the lifespan of the object associated with the id.
The scope attribute has four possible values: (a) page, (b)request, (c)session, and (d) application.
The <jsp:include> Action
This action lets you insert files into the page being generated. The syntax looks like this −
<jsp:include page = "relative URL" flush = "true" />
Unlike the include directive, which inserts the file at the time the JSP page is translated into a servlet,
this action inserts the file at the time the page is requested.
Following table lists out the attributes associated with the include action −
S.No. Attribute & Description

page
1
The relative URL of the page to be included.

flush
2 The boolean attribute determines whether the included resource has its buffer flushed
before it is included.
Example
Let us define the following two files (a)date.jsp and (b) main.jsp as follows −
Following is the content of the date.jsp file −
<p>Today's date: <%= (new java.util.Date()).toLocaleString()%></p>
Following is the content of the main.jsp file −
<html>
<head>
<title>The include Action Example</title>
</head>

<body>
<center>
<h2>The include action Example</h2>
<jsp:include page = "date.jsp" flush = "true" />
</center>
</body></html>
Let us now keep all these files in the root directory and try to access main.jsp. You will receive the
following output −

The include action Example

Today's date: 12-Sep-2010 14:54:22

The <jsp:useBean> Action


The useBean action is quite versatile. It first searches for an existing object utilizing the id and scope
variables. If an object is not found, it then tries to create the specified object.
The simplest way to load a bean is as follows −
<jsp:useBean id = "name" class = "package.class" />
Once a bean class is loaded, you can use jsp:setProperty and jsp:getProperty actions to modify
and retrieve the bean properties.
Following table lists out the attributes associated with the useBean action −

22
S.No. Attribute & Description

class
1
Designates the full package name of the bean.

type
2
Specifies the type of the variable that will refer to the object.

beanName
3 Gives the name of the bean as specified by the instantiate () method of the
java.beans.Beans class.
Let us now discuss the jsp:setProperty and the jsp:getProperty actions before giving a valid
example related to these actions.
The <jsp:setProperty> Action
The setProperty action sets the properties of a Bean. The Bean must have been previously defined
before this action. There are two basic ways to use the setProperty action −
You can use jsp:setProperty after, but outside of a jsp:useBean element, as given below −
<jsp:useBean id = "myName" ... />
...
<jsp:setProperty name = "myName" property = "someProperty" .../>
In this case, the jsp:setProperty is executed regardless of whether a new bean was instantiated or an
existing bean was found.
A second context in which jsp:setProperty can appear is inside the body of a jsp:useBean element,
as given below −
<jsp:useBean id = "myName" ... >
...
<jsp:setProperty name = "myName" property = "someProperty" .../></jsp:useBean>
Here, the jsp:setProperty is executed only if a new object was instantiated, not if an existing one was
found.
Following table lists out the attributes associated with the setProperty action −
S.No. Attribute & Description

name
1 Designates the bean the property of which will be set. The Bean must have been
previously defined.

property
Indicates the property you want to set. A value of "*" means that all request
2
parameters whose names match bean property names will be passed to the
appropriate setter methods.

value
3 The value that is to be assigned to the given property. The the parameter's value is
null, or the parameter does not exist, the setProperty action is ignored.

param
4
The param attribute is the name of the request parameter whose value the property is

23
to receive. You can't use both value and param, but it is permissible to use neither.
The <jsp:getProperty> Action
The getProperty action is used to retrieve the value of a given property and converts it to a string,
and finally inserts it into the output.
The getProperty action has only two attributes, both of which are required. The syntax of the
getProperty action is as follows −
<jsp:useBean id = "myName" ... />
...<jsp:getProperty name = "myName" property = "someProperty" .../>
Following table lists out the required attributes associated with the getProperty action −
S.No. Attribute & Description

name
1 The name of the Bean that has a property to be retrieved. The Bean must have been
previously defined.

property
2
The property attribute is the name of the Bean property to be retrieved.
Example
Let us define a test bean that will further be used in our example −
/* File: TestBean.java */package action;
public class TestBean {
private String message = "No message specified";

public String getMessage() {


return(message);
}
public void setMessage(String message) {
this.message = message;
}}
Compile the above code to the generated TestBean.class file and make sure that you copied the
TestBean.class in C:\apache-tomcat-7.0.2\webapps\WEB-INF\classes\action folder and
the CLASSPATH variable should also be set to this folder −
Now use the following code in main.jsp file. This loads the bean and sets/gets a simple String
parameter −
<html>

<head>
<title>Using JavaBeans in JSP</title>
</head>

<body>
<center>
<h2>Using JavaBeans in JSP</h2>
<jsp:useBean id = "test" class = "action.TestBean" />
<jsp:setProperty name = "test" property = "message"
value = "Hello JSP..." />

24
<p>Got message....</p>
<jsp:getProperty name = "test" property = "message" />
</center>
</body></html>
Let us now try to access main.jsp, it would display the following result −

Using JavaBeans in JSP

Got message....
Hello JSP...

The <jsp:forward> Action


The forward action terminates the action of the current page and forwards the request to another
resource such as a static page, another JSP page, or a Java Servlet.
Following is the syntax of the forward action −
<jsp:forward page = "Relative URL" />
Following table lists out the required attributes associated with the forward action −
S.No. Attribute & Description

page
1 Should consist of a relative URL of another resource such as a static page, another
JSP page, or a Java Servlet.
Example
Let us reuse the following two files (a) date.jsp and (b) main.jsp as follows −
Following is the content of the date.jsp file −
<p>Today's date: <%= (new java.util.Date()).toLocaleString()%></p>
Following is the content of the main.jsp file −
<html>
<head>
<title>The include Action Example</title>
</head>

<body>
<center>
<h2>The include action Example</h2>
<jsp:forward page = "date.jsp" />
</center>
</body></html>
Let us now keep all these files in the root directory and try to access main.jsp. This would display
result something like as below.
Here it discarded the content from the main page and displayed the content from forwarded page
only.

Today's date: 12-Sep-2010 14:54:22

The <jsp:plugin> Action


The plugin action is used to insert Java components into a JSP page. It determines the type of
browser and inserts the <object> or <embed> tags as needed.

25
If the needed plugin is not present, it downloads the plugin and then executes the Java component.
The Java component can be either an Applet or a JavaBean.
The plugin action has several attributes that correspond to common HTML tags used to format Java
components. The <param> element can also be used to send parameters to the Applet or Bean.
Following is the typical syntax of using the plugin action −
<jsp:plugin type = "applet" codebase = "dirname" code = "MyApplet.class"
width = "60" height = "80">
<jsp:param name = "fontcolor" value = "red" />
<jsp:param name = "background" value = "black" />

<jsp:fallback>
Unable to initialize Java Plugin
</jsp:fallback>
</jsp:plugin>
You can try this action using some applet if you are interested. A new element,
the <fallback> element, can be used to specify an error string to be sent to the user in case the
component fails.
The <jsp:element> Action

The <jsp:attribute> Action

The <jsp:body> Action

The <jsp:element>, <jsp:attribute> and <jsp:body> actions are used to define XML elements
dynamically. The word dynamically is important, because it means that the XML elements can be
generated at request time rather than statically at compile time.
Following is a simple example to define XML elements dynamically −
<%@page language = "java" contentType = "text/html"%><html xmlns =
"http://www.w3c.org/1999/xhtml"
xmlns:jsp = "http://java.sun.com/JSP/Page">

<head><title>Generate XML Element</title></head>

<body>
<jsp:element name = "xmlElement">
<jsp:attribute name = "xmlElementAttr">
Value for the attribute
</jsp:attribute>

<jsp:body>
Body for XML element
</jsp:body>

</jsp:element>
</body></html>
This would produce the following HTML code at run time −
<html xmlns = "http://www.w3c.org/1999/xhtml" xmlns:jsp = "http://java.sun.com/JSP/Page">
<head><title>Generate XML Element</title></head>

26
<body>
<xmlElement xmlElementAttr = "Value for the attribute">
Body for XML element
</xmlElement>
</body></html>
The <jsp:text> Action
The <jsp:text> action can be used to write the template text in JSP pages and documents. Following
is the simple syntax for this action −
<jsp:text>Template data</jsp:text>
The body of the template cannot contain other elements; it can only contain text and EL expressions
(Note − EL expressions are explained in a subsequent chapter). Note that in XML files, you cannot
use expressions such as ${whatever > 0}, because the greater than signs are illegal. Instead, use
the gt form, such as ${whatever gt 0} or an alternative is to embed the value in a CDATA section.
<jsp:text><![CDATA[<br>]]></jsp:text>
If you need to include a DOCTYPE declaration, for instance for XHTML, you must also use
the <jsp:text> element as follows −
<jsp:text><![CDATA[<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"DTD/xhtml1-strict.dtd">]]></jsp:text>

<head><title>jsp:text action</title></head>

<body>
<books><book><jsp:text>
Welcome to JSP Programming
</jsp:text></book></books>
</body></html>
Try the above example with and without <jsp:text> action
In this chapter, we will discuss Client Request in JSP. When a browser requests for a Webpage, it
sends a lot of information to the web server. This information cannot be read directly because this
information travels as a part of header of HTTP request. You can check HTTP Protocol for more
information on this.
Following table lists out the important header information which comes from the browser. This
information is frequently used in web programming −
S.No. Header & Description

Accept
1 This header specifies the MIME types that the browser or other clients can handle.
Values of image/png or image/jpeg are the two most common possibilities.

Accept-Charset
2 This header specifies the character sets that the browser can use to display the
information. For example, ISO-8859-1.

Accept-Encoding
3 This header specifies the types of encodings that the browser knows how to handle.
Values of gzip or compress are the two most common possibilities.

4 Accept-Language

27
This header specifies the client's preferred languages in case the servlet can produce
results in more than one language. For example en, en-us, ru, etc.

Authorization
5 This header is used by clients to identify themselves when accessing password-
protected webpages.

Connection
This header indicates whether the client can handle persistent HTTP connections.
6 Persistent connections permit the client or other browser to retrieve multiple files
with a single request. A value of Keep-Alive means that persistent connections
should be used.

Content-Length
7 This header is applicable only to POST requests and gives the size of the POST data
in bytes.

Cookie
8
This header returns cookies to servers that previously sent them to the browser.

Host
9
This header specifies the host and port as given in the original URL.

If-Modified-Since
This header indicates that the client wants the page only if it has been changed after
10
the specified date. The server sends a code, 304 which means Not Modified header
if no newer result is available.

If-Unmodified-Since
11 This header is the reverse of If-Modified-Since; it specifies that the operation should
succeed only if the document is older than the specified date.

Referer
This header indicates the URL of the referring webpages. For example, if you are at
12
Webpage 1 and click on a link to Webpage 2, the URL of Webpage 1 is included in
the Referer header when the browser requests Webpage 2.

User-Agent
13 This header identifies the browser or other client making the request and can be used
to return different content to different types of browsers.
The HttpServletRequest Object
The request object is an instance of a javax.servlet.http.HttpServletRequest object. Each time a
client requests a page, the JSP engine creates a new object to represent that request.
The request object provides methods to get HTTP header information including form data, cookies,
HTTP methods, etc.
Following table lists out the important methods that can be used to read HTTP header in your JSP
program. These methods are available with HttpServletRequest object which represents client request
to webserver.

28
S.No. Method & Description

Cookie[] getCookies()
1
Returns an array containing all of the Cookie objects the client sent with this request.

Enumeration getAttributeNames()
2 Returns an Enumeration containing the names of the attributes available to this
request.

Enumeration getHeaderNames()
3
Returns an enumeration of all the header names this request contains.

Enumeration getParameterNames()
4 Returns an enumeration of String objects containing the names of the parameters
contained in this request.

HttpSession getSession()
5 Returns the current session associated with the this request, or if the request does not
have a session, creates one.

HttpSession getSession(boolean create)


6 Returns the current HttpSession associated with the this request or, if if there is no
current session and create is true, returns a new session.

Locale getLocale()
7 Returns the preferred Locale that the client will accept content in, based on the
Accept-Language header.

Object getAttribute(String name)


8 Returns the value of the named attribute as an Object, or null if no attribute of the
given name exists.

ServletInputStream getInputStream()
9
Retrieves the body of the request as binary data using a ServletInputStream.

String getAuthType()
10 Returns the name of the authentication scheme used to protect the servlet, for
example, "BASIC" or "SSL," or null if the JSP was not protected.

String getCharacterEncoding()
11
Returns the name of the character encoding used in the body of this request.

String getContentType()
12
Returns the MIME type of the body of the request, or null if the type is not known.

String getContextPath()
13
Returns the portion of the request URI that indicates the context of the request.

29
String getHeader(String name)
14
Returns the value of the specified request header as a String.

String getMethod()
15 Returns the name of the HTTP method with which this request was made, for
example, GET, POST, or PUT.

String getParameter(String name)


16 Returns the value of a request parameter as a String, or null if the parameter does not
exist.

String getPathInfo()
17 Returns any extra path information associated with the URL the client sent when it
made this request.

String getProtocol()
18
Returns the name and version of the protocol the request uses.

String getQueryString()
19
Returns the query string that is contained in the request URL after the path.

String getRemoteAddr()
20
Returns the Internet Protocol (IP) address of the client that sent the request.

String getRemoteHost()
21
Returns the fully qualified name of the client that sent the request.

String getRemoteUser()
22 Returns the login of the user making this request, if the user has been authenticated,
or null if the user has not been authenticated.

String getRequestURI()
23 Returns the part of this request's URL from the protocol name up to the query string
in the first line of the HTTP request.

String getRequestedSessionId()
24
Returns the session ID specified by the client.

String getServletPath()
25
Returns the part of this request's URL that calls the JSP.

String[] getParameterValues(String name)


26 Returns an array of String objects containing all of the values the given request
parameter has, or null if the parameter does not exist.

boolean isSecure()
27 Returns a boolean indicating whether this request was made using a secure channel,
such as HTTPS.

30
int getContentLength()
28 Returns the length, in bytes, of the request body and made available by the input
stream, or -1 if the length is not known.

int getIntHeader(String name)


29
Returns the value of the specified request header as an int.

int getServerPort()
30
Returns the port number on which this request was received.
HTTP Header Request Example
Following is the example which uses getHeaderNames() method of HttpServletRequest to read the
HTTP header information. This method returns an Enumeration that contains the header information
associated with the current HTTP request.
Once we have an Enumeration, we can loop down the Enumeration in the standard manner. We will
use the hasMoreElements() method to determine when to stop and the nextElement() method to get
the name of each parameter name.
<%@ page import = "java.io.*,java.util.*" %>
<html>
<head>
<title>HTTP Header Request Example</title>
</head>

<body>
<center>
<h2>HTTP Header Request Example</h2>

<table width = "100%" border = "1" align = "center">


<tr bgcolor = "#949494">
<th>Header Name</th>
<th>Header Value(s)</th>
</tr>
<%
Enumeration headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements()) {
String paramName = (String)headerNames.nextElement();
out.print("<tr><td>" + paramName + "</td>\n");
String paramValue = request.getHeader(paramName);
out.println("<td> " + paramValue + "</td></tr>\n");
}
%>
</table>
</center>

</body></html>
Let us now put the above code in main.jsp and try to access it.

JSP RESPONSE
n this chapter, we will discuss the Server Response in JSP. When a Web server responds to a HTTP
request, the response typically consists of a status line, some response headers, a blank line, and the
document. A typical response looks like this −

31
HTTP/1.1 200 OKContent-Type: text/htmlHeader2: ......HeaderN: ...
(Blank Line)<!doctype ...>
<html>
<head>...</head>
<body>
...
</body></html>
The status line consists of the HTTP version (HTTP/1.1 in the example), a status code (200 in the
example), and a very short message corresponding to the status code (OK in the example).
Following is a summary of the most useful HTTP 1.1 response headers which go back to the browser
from the web server. These headers are frequently used in web programming −
S.No. Header & Description

Allow
1 This header specifies the request methods (GET, POST, etc.) that the server
supports.

Cache-Control
This header specifies the circumstances in which the response document can safely
be cached. It can have values public, private or no-cache etc. Public means
2
document is cacheable, Private means document is for a single user and can only be
stored in private (nonshared) caches and no-cache means document should never be
cached.

Connection
This header instructs the browser whether to use persistent HTTP connections or not.
3
A value of close instructs the browser not to use persistent HTTP connections
and keep-alive means using persistent connections.

Content-Disposition
4 This header lets you request that the browser ask the user to save the response to disk
in a file of the given name.

Content-Encoding
5
This header specifies the way in which the page was encoded during transmission.

Content-Language
6 This header signifies the language in which the document is written. For
example, en, en-us, ru, etc.

Content-Length
7 This header indicates the number of bytes in the response. This information is
needed only if the browser is using a persistent (keep-alive) HTTP connection.

Content-Type
8 This header gives the MIME (Multipurpose Internet Mail Extension) type of the
response document.

32
Expires
9 This header specifies the time at which the content should be considered out-of-date
and thus no longer be cached.

Last-Modified
This header indicates when the document was last changed. The client can then
10
cache the document and supply a date by an If-Modified-Since request header in
later requests.

Location
This header should be included with all responses that have a status code in the 300s.
11
This notifies the browser of the document address. The browser automatically
reconnects to this location and retrieves the new document.

Refresh
12 This header specifies how soon the browser should ask for an updated page. You can
specify time in number of seconds after which a page would be refreshed.

Retry-After
13 This header can be used in conjunction with a 503 (Service Unavailable) response
to tell the client how soon it can repeat its request.

Set-Cookie
14
This header specifies a cookie associated with the page.
The HttpServletResponse Object
The response object is an instance of a javax.servlet.http.HttpServletResponse object. Just as the
server creates the request object, it also creates an object to represent the response to the client.
The response object also defines the interfaces that deal with creating new HTTP headers. Through
this object, the JSP programmer can add new cookies or date stamps, HTTP status codes etc.
The following methods can be used to set HTTP response header in your servlet program. These
methods are available with the HttpServletResponse object. This object represents the server
response.
S.No. Method & Description

String encodeRedirectURL(String url)


1 Encodes the specified URL for use in the sendRedirect method or, if encoding is not
needed, returns the URL unchanged.

String encodeURL(String url)


2 Encodes the specified URL by including the session ID in it, or, if encoding is not
needed, returns the URL unchanged.

boolean containsHeader(String name)


3 Returns a boolean indicating whether the named response header has already been
set.

4 boolean isCommitted()

33
Returns a boolean indicating if the response has been committed.

void addCookie(Cookie cookie)


5
Adds the specified cookie to the response.

void addDateHeader(String name, long date)


6
Adds a response header with the given name and date-value.

void addHeader(String name, String value)


7
Adds a response header with the given name and value.

void addIntHeader(String name, int value)


8
Adds a response header with the given name and integer value.

void flushBuffer()
9
Forces any content in the buffer to be written to the client.

void reset()
10
Clears any data that exists in the buffer as well as the status code and headers.

void resetBuffer()
11 Clears the content of the underlying buffer in the response without clearing headers
or status code.

void sendError(int sc)


12 Sends an error response to the client using the specified status code and clearing the
buffer.

void sendError(int sc, String msg)


13
Sends an error response to the client using the specified status.

void sendRedirect(String location)


14 Sends a temporary redirect response to the client using the specified redirect location
URL.

void setBufferSize(int size)


15
Sets the preferred buffer size for the body of the response.

void setCharacterEncoding(String charset)


16 Sets the character encoding (MIME charset) of the response being sent to the client,
for example, to UTF-8.

void setContentLength(int len)


17 Sets the length of the content body in the response In HTTP servlets; this method
also sets the HTTP Content-Length header.

void setContentType(String type)


18
Sets the content type of the response being sent to the client, if the response has not

34
been committed yet.

void setDateHeader(String name, long date)


19
Sets a response header with the given name and date-value.

void setHeader(String name, String value)


20
Sets a response header with the given name and value.

void setIntHeader(String name, int value)


21
Sets a response header with the given name and integer value.

void setLocale(Locale loc)


22
Sets the locale of the response, if the response has not been committed yet.

void setStatus(int sc)


23
Sets the status code for this response.
HTTP Header Response Example
Following example would use setIntHeader() method to set Refresh header to simulate a digital
clock −
<%@ page import = "java.io.*,java.util.*" %>
<html>

<head>
<title>Auto Refresh Header Example</title>
</head>

<body>
<center>
<h2>Auto Refresh Header Example</h2>
<%
// Set refresh, autoload time as 5 seconds
response.setIntHeader("Refresh", 5);

// Get current time


Calendar calendar = new GregorianCalendar();

String am_pm;
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);

if(calendar.get(Calendar.AM_PM) == 0)
am_pm = "AM";
else
am_pm = "PM";
String CT = hour+":"+ minute +":"+ second +" "+ am_pm;
out.println("Current Time is: " + CT + "\n");
%>

35
</center>

</body></html>
Now put the above code in main.jsp and try to access it. This will display the current system time
after every 5 seconds as follows. Run the JSP. You will receive the following output: −

Regular HTML, of course, cannot contain dynamic information.

36
Remote method invocation

The RMI (Remote Method Invocation) is an API that provides a mechanism to create distributed
application in java. The RMI allows an object to invoke methods on an object running in another
JVM.
RMI uses stub and skeleton object for communication with the remote object.
A remote object is an object whose method can be invoked from another JVM. It is a mechanism that
allows an object residing in one system (JVM) to access/invoke an object running on another JVM.
RMI is used to build distributed applications; it provides remote communication between Java
programs. It is provided in the package java.rmi.

Understanding stub and skeleton


RMI uses stub and skeleton object for communication with the remote object.
A remote object is an object whose method can be invoked from another JVM. Let's understand the
stub and skeleton objects:
stub
The stub is an object, acts as a gateway for the client side. All the outgoing requests are routed
through it. It resides at the client side and represents the remote object. When the caller invokes
method on the stub object, it does the following tasks:
1. It initiates a connection with remote Virtual Machine (JVM),
2. It writes and transmits (marshals) the parameters to the remote Virtual Machine (JVM),
3. It waits for the result
4. It reads (unmarshals) the return value or exception, and
5. It finally, returns the value to the caller.
skeleton
The skeleton is an object, acts as a gateway for the server side object. All the incoming requests are
routed through it. When the skeleton receives the incoming request, it does the following tasks:
I. It reads the parameter for the remote method
II. It invokes the method on the actual remote object, and
III. It writes and transmits (marshals) the result to the caller.
Architecture of an RMI Application
In an RMI application, we write two programs, a server program (resides on the server) and a client
program (resides on the client).
Inside the server program, a remote object is created and reference of that object is made
available for the client (using the registry).
The client program requests the remote objects on the server and tries to invoke its methods.
The following diagram shows the architecture of an RMI application.

37
Let us now discuss the components of this architecture.

Transport Layer − This layer connects the client and the server. It manages the existing
connection and also sets up new connections.
Stub − A stub is a representation (proxy) of the remote object at client. It resides in the client
system; it acts as a gateway for the client program.
Skeleton − This is the object which resides on the server side. stub communicates with this
skeleton to pass request to the remote object.
RRL(Remote Reference Layer) − It is the layer which manages the references made by the
client to the remote object.

Working of an RMI Application


The following points summarize how an RMI application works −

When the client makes a call to the remote object, it is received by the stub which eventually
passes this request to the RRL.

When the client-side RRL receives the request, it invokes a method called invoke() of the
object remoteRef. It passes the request to the RRL on the server side.
The RRL on the server side passes the request to the Skeleton (proxy on the server) which
finally invokes the required object on the server.
The result is passed all the way back to the client.

Marshalling and Unmarshalling


Whenever a client invokes a method that accepts parameters on a remote object, the parameters are
bundled into a message before being sent over the network. These parameters may be of primitive
type or objects. In case of primitive type, the parameters are put together and a header is attached to
it. In case the parameters are objects, then they are serialized. This process is known as marshalling.
At the server side, the packed parameters are unbundled and then the required method is invoked.
This process is known as unmarshalling.
RMI Registry
RMI registry is a namespace on which all server objects are placed. Each time the server creates an
object, it registers this object with the RMIregistry (using bind() or reBind() methods). These are
registered using a unique name known as bind name.

38
To invoke a remote object, the client needs a reference of that object. At that time, the client fetches
the object from the registry using its bind name (using lookup() method).
The following illustration explains the entire process −

Goals of RMI
Following are the goals of RMI −
To minimize the complexity of the application.
To preserve type safety.
Distributed garbage collection.
Minimize the difference between working with local and remote objec

RMI Java application


To write an RMI Java application, you would have to follow the steps given below −
 Define the remote interface
 Develop the implementation class (remote object)
 Develop the server program
 Develop the client program
 Compile the application
 Execute the application
Defining the Remote Interface
A remote interface provides the description of all the methods of a particular remote object. The
client communicates with this remote interface.
To create a remote interface −

Create an interface that extends the predefined interface Remote which belongs to the
package.

Declare all the business methods that can be invoked by the client in this interface.
Since there is a chance of network issues during remote calls, an exception
named RemoteException may occur; throw it.

Following is an example of a remote interface. Here we have defined an interface with the
name Hello and it has a method called printMsg().

39
import java.rmi.Remote; import java.rmi.RemoteException;
// Creating Remote interface for our application public interface Hello extends Remote {
void printMsg() throws RemoteException; }
Developing the Implementation Class (Remote Object)
We need to implement the remote interface created in the earlier step. (We can write an
implementation class separately or we can directly make the server program implement this
interface.)
To develop an implementation class −
 Implement the interface created in the previous step.
 Provide implementation to all the abstract methods of the remote interface.
Following is an implementation class. Here, we have created a class named ImplExample and
implemented the interface Hello created in the previous step and provided body for this method
which prints a message.
// Implementing the remote interface public class ImplExample implements Hello {

// Implementing the interface method


public void printMsg() {
System.out.println("This is an example RMI program");
} }
Developing the Server Program
An RMI server program should implement the remote interface or extend the implementation class.
Here, we should create a remote object and bind it to the RMIregistry.
To develop a server program −

Create a client class from where you want invoke the remote object.
Create a remote object by instantiating the implementation class as shown below.
Export the remote object using the method exportObject() of the class
named UnicastRemoteObject which belongs to the package java.rmi.server.
Get the RMI registry using the getRegistry() method of the LocateRegistry class which
belongs to the package java.rmi.registry.

Bind the remote object created to the registry using the bind() method of the class
named Registry. To this method, pass a string representing the bind name and the object
exported, as parameters.

Following is an example of an RMI server program.


import java.rmi.registry.Registry; import java.rmi.registry.LocateRegistry; import
java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject;
public class Server extends ImplExample {
public Server() {}
public static void main(String args[]) {
try {
// Instantiating the implementation class
ImplExample obj = new ImplExample();

// Exporting the object of implementation class


// (here we are exporting the remote object to the stub)
Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0);

40
// Binding the remote object (stub) in the registry
Registry registry = LocateRegistry.getRegistry();

registry.bind("Hello", stub);
System.err.println("Server ready");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}}
Developing the Client Program
Write a client program in it, fetch the remote object and invoke the required method using this object.
To develop a client program −

Create a client class from where your intended to invoke the remote object.
Get the RMI registry using the getRegistry() method of the LocateRegistry class which
belongs to the package java.rmi.registry.
Fetch the object from the registry using the method lookup() of the class Registry which
belongs to the package java.rmi.registry.
To this method, you need to pass a string value representing the bind name as a parameter.
This will return you the remote object.
The lookup() returns an object of type remote, down cast it to the type Hello.
Finally invoke the required method using the obtained remote object.
Following is an example of an RMI client program.
import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry;
public class Client {
private Client() {}
public static void main(String[] args) {
try {
// Getting the registry
Registry registry = LocateRegistry.getRegistry(null);

// Looking up the registry for the remote object


Hello stub = (Hello) registry.lookup("Hello");

// Calling the remote method using the obtained object


stub.printMsg();

// System.out.println("Remote method invoked");


} catch (Exception e) {
System.err.println("Client exception: " + e.toString());
e.printStackTrace();
}
}}
Compiling the Application
To compile the application −
 Compile the Remote interface.
 Compile the implementation class.
 Compile the server program.
 Compile the client program.

41
Or,

In the previous chapter, we created a sample RMI application where a client invokes a method which
displays a GUI window (JavaFX).

In this chapter, we will take an example to see how a client program can retrieve the records of a
table in MySQL database residing on the server.

Assume we have a table named student_data in the database details as shown below.

+----+--------+--------+------------+---------------------+
| ID | NAME | BRANCH | PERCENTAGE | EMAIL |
+----+--------+--------+------------+---------------------+
| 1 | Ram | IT | 85 | [email protected] |
| 2 | Rahim | EEE | 95 | [email protected] |
| 3 | Robert | ECE | 90 | [email protected] |
+----+--------+--------+------------+---------------------+
Assume the name of the user is myuser and its password is password.

Creating a Student Class


Create a Student class with setter and getter methods as shown below.

public class Student implements java.io.Serializable {


private int id, percent;
private String name, branch, email;

public int getId() {


return id;
}
public String getName() {
return name;
}
public String getBranch() {
return branch;
}
public int getPercent() {
return percent;
}
public String getEmail() {
return email;
}
public void setID(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setBranch(String branch) {
this.branch = branch;
}

42
public void setPercent(int percent) {
this.percent = percent;
}
public void setEmail(String email) {
this.email = email;
}
}
Defining the Remote Interface
Define the remote interface. Here, we are defining a remote interface named Hello with a method
named getStudents () in it. This method returns a list which contains the object of the class Student.

import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.*;

// Creating Remote interface for our application


public interface Hello extends Remote {
public List<Student> getStudents() throws Exception;
}
Developing the Implementation Class
Create a class and implement the above created interface.

Here we are implementing the getStudents() method of the Remote interface. When you invoke this
method, it retrieves the records of a table named student_data. Sets these values to the Student class
using its setter methods, adds it to a list object and returns that list.

import java.sql.*;
import java.util.*;

// Implementing the remote interface


public class ImplExample implements Hello {

// Implementing the interface method


public List<Student> getStudents() throws Exception {
List<Student> list = new ArrayList<Student>();

// JDBC driver name and database URL


String JDBC_DRIVER = "com.mysql.jdbc.Driver";
String DB_URL = "jdbc:mysql://localhost:3306/details";

// Database credentials
String USER = "myuser";
String PASS = "password";

Connection conn = null;


Statement stmt = null;

//Register JDBC driver


Class.forName("com.mysql.jdbc.Driver");

43
//Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");

//Execute a query
System.out.println("Creating statement...");

stmt = conn.createStatement();
String sql = "SELECT * FROM student_data";
ResultSet rs = stmt.executeQuery(sql);

//Extract data from result set


while(rs.next()) {
// Retrieve by column name
int id = rs.getInt("id");

String name = rs.getString("name");


String branch = rs.getString("branch");

int percent = rs.getInt("percentage");


String email = rs.getString("email");

// Setting the values


Student student = new Student();
student.setID(id);
student.setName(name);
student.setBranch(branch);
student.setPercent(percent);
student.setEmail(email);
list.add(student);
}
rs.close();
return list;
}
}
Server Program
An RMI server program should implement the remote interface or extend the implementation class.
Here, we should create a remote object and bind it to the RMI registry.

Following is the server program of this application. Here, we will extend the above created class,
create a remote object and register it to the RMI registry with the bind name hello.

import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class Server extends ImplExample {


public Server() {}

44
public static void main(String args[]) {
try {
// Instantiating the implementation class
ImplExample obj = new ImplExample();

// Exporting the object of implementation class (


here we are exporting the remote object to the stub)
Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0);

// Binding the remote object (stub) in the registry


Registry registry = LocateRegistry.getRegistry();

registry.bind("Hello", stub);
System.err.println("Server ready");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}
Client Program
Following is the client program of this application. Here, we are fetching the remote object and
invoking the method named getStudents(). It retrieves the records of the table from the list object and
displays them.

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.*;

public class Client {


private Client() {}
public static void main(String[] args)throws Exception {
try {
// Getting the registry
Registry registry = LocateRegistry.getRegistry(null);

// Looking up the registry for the remote object


Hello stub = (Hello) registry.lookup("Hello");

// Calling the remote method using the obtained object


List<Student> list = (List)stub.getStudents();
for (Student s:list)v {

// System.out.println("bc "+s.getBranch());
System.out.println("ID: " + s.getId());
System.out.println("name: " + s.getName());
System.out.println("branch: " + s.getBranch());
System.out.println("percent: " + s.getPercent());
System.out.println("email: " + s.getEmail());
}

45
// System.out.println(list);
} catch (Exception e) {
System.err.println("Client exception: " + e.toString());
e.printStackTrace();
}
}
}

46

You might also like