0% found this document useful (0 votes)
3 views31 pages

Module - 4 Servlets

Module-4 introduces servlets, explaining their life cycle, architecture, and the use of Tomcat for servlet development. It highlights the differences between servlets and CGI, emphasizing servlets' efficiency and capabilities in handling dynamic web content. The module also covers the Servlet API, advantages of Java servlets, and provides guidance on installing and using Tomcat for servlet applications.

Uploaded by

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

Module - 4 Servlets

Module-4 introduces servlets, explaining their life cycle, architecture, and the use of Tomcat for servlet development. It highlights the differences between servlets and CGI, emphasizing servlets' efficiency and capabilities in handling dynamic web content. The module also covers the Servlet API, advantages of Java servlets, and provides guidance on installing and using Tomcat for servlet applications.

Uploaded by

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

Advanced Java (ISE23404) Module-4

Module-4
Introducing servlets
Introducing servlets: Background; The Life Cycle of a Servlet; Using Tomcat for Servlet Development;
A simple Servlet; The Servlet API; The Jakarta. Servlet Package; Reading Servlet Parameter; The
[Link] package; Handling HTTP Requests and Responses; Using Cookies; Session
Tracking. Java Server Pages (JSP); JSP tags, Variables and Objects, Methods, Control statements,
Loops, Request String, Parsing other information, User sessions, Cookies, Session Objects.

Background
Servlets are the Java programs that run on the Java-enabled web server or application server. They are used to
handle the request obtained from the webserver, process the request, produce the response, then send a response
back to the webserver. Properties of Servlets are as follows:
• Servlets work on the server-side.
• Servlets are capable of handling complex requests obtained from the webserver.
Servlet Architecture is can be depicted from the image itself as provided below as follows:

Execution of Servlets basically involves six basic steps:


1. The clients send the request to the webserver.
2. The web server receives the request.
3. The web server passes the request to the corresponding servlet.
4. The servlet processes the request and generates the response in the form of output.
5. The servlet sends the response back to the webserver.
6. The web server sends the response back to the client and the client browser displays it on the screen.

Now let us do discuss eccentric point that why do we need For Server-Side extensions?

The server-side extensions are nothing but the technologies that are used to create dynamic Web pages. Actually, to
provide the facility of dynamic Web pages, Web pages need a container or Web server. To meet this requirement,
independent Web server providers offer some proprietary solutions in the form of APIs(Application Programming
Interface). These APIs allow us to build programs that can run with a Web server. In this case, Java Servlet is also one
of the component APIs of Java Platform Enterprise Edition which sets standards for creating dynamic Web applications

pg. 1 Dept of ISE , GAT


Advanced Java (ISE23404) Module-4

in Java. The Servlet technology is similar to other Web server extensions such as scripts and Hypertext
Preprocessor (PHP). However, Java Servlets are more acceptable since they solve the limitations of CGI such as low
performance and low degree scalability.

What is CGI?

CGI is actually an external application that is written by using any of the programming languages like C or C++ and this
is responsible for processing client requests and generating dynamic content
In CGI application, when a client makes a request to access dynamic Web pages, the Web server performs the following
operations :
• It first locates the requested web page i.e the required CGI application using URL.
• It then creates a new process to service the client’s request.
• Invokes the CGI application within the process and passes the request information to the application. • Collects
the response from the CGI application.
 Destroys the process, prepares the HTTP response, and sends it to the client.

So, in CGI server has to create and destroy the process for every request. It’s easy to understand that this approach is
applicable for handling few clients but as the number of clients increases, the workload on the server increases and so
the time is taken to process requests increases.

Difference between Servlet and CGI


Servlet CGI(Common Gateway Interface)

Servlets are portable and efficient. CGI is not portable

In Servlets, sharing data is possible. In CGI, sharing data is not possible.

Servlets can directly communicate with the CGI cannot directly communicate with the
webserver. webserver.

Servlets are less expensive than CGI. CGI is more expensive than Servlets.

Servlets can handle the cookies. CGI cannot handle the cookies.

pg. 2 Dept of ISE , GAT


Advanced Java (ISE23404) Module-4

The Life Cycle of a Servlet

Each servlet has the same life cycle:

 A server loads and initializes the servlet

 The servlet handles zero or more client requests

 The server removes the servlet


(some servers do this step only when they shut down)

Initializing a Servlet

When a server loads a servlet, the server runs the servlet's init method. Initialization completes before client
requests are handled and before the servlet is destroyed.

Even though most servlets are run in multi-threaded servers, servlets have no concurrency issues during servlet
initialization. The server calls the init method once, when the server loads the servlet, and will not call the
init method again unless the server is reloading the servlet. The server can not reload a servlet until after the
server has destroyed the servlet by calling the destroy method.

Using Tomcat for Servlet Development

What is Tomcat ?
Tomcat is an open-source web server and servlet. The Apache Software Foundation has developed it. It is
used widely for hosting Java-based applications on the web. It is built on Java technologies and implements
the Java Servlet and JavaServer Pages (JSP) specifications. Tomcat acts as a bridge between web servers and
Java-based applications, facilitating the execution of dynamic content and processing client requests.

Tomcat offers a lightweight and efficient solution for hosting Java web applications. Tomcat is popular for
several reasons. Its scalability is admired by many. Tomcat's robustness is useful. It has great community
support which brings relief to the users. With its modular architecture and adherence to industry standards,
Tomcat enables developers to build and deploy web applications with ease.

pg. 3 Dept of ISE , GAT


Advanced Java (ISE23404) Module-4

How Does Tomcat Work?

Tomcat follows a modular architecture comprising connectors, containers, and the Catalina Servlet container.
This architecture enables Tomcat to efficiently handle client requests and generate responses.

Connectors are in charge of accepting and processing requests that the clients sent to Tomcat. In order to have
a connection with the client, different protocols are used by the connectors. These connectors can be HTTP or
HTTPS. They handle tasks like connection management, request parsing, and data transmission.

Once a request is received, connectors pass it to the appropriate container based on the requested URL.
Containers manage the lifecycle of web applications and execute Java servlets or JSP code to generate
responses. They provide an environment for running web applications, managing resources, and handling
concurrent requests.

The Catalina Servlet container, in particular, is responsible for mapping requests to the appropriate servlet and
managing the servlet's life cycle. It handles the process of generating dynamic content by executing servlet
code and producing the response that is sent back to the client.

Tomcat's modular architecture allows for flexibility and extensibility. Developers can add or customize
components to enhance the functionality of Tomcat according to their specific requirements.

If you are wondering what Tomcat is, it is an open-source web server and servlet. The Apache Software
Foundation has developed it. It is used widely for hosting Java-based applications on the web.

In this comprehensive article, we will explore the various aspects of Tomcat, including its definition,
functionality, installation process on Windows, application deployment, a comparison with other web
servers, and commonly asked questions. You will have a deep understanding of what Tomcat is all about
and what Tomcat is used for when you finish reading this article. You will also understand why Tomcat is
important in the world of web development.

How to Install Tomcat on Windows?

Step 1. Command-line installation

Installing Tomcat on Windows is easy. It is a step-by-step process. Go to the Apache Tomcat website. Once
you go there, check for the recent Tomcat version and download it. You should check what your system needs
before you download it. Also, check the capacity of your system.

When the download is done, the downloaded archive should be extracted. Save the downloaded file in a
directory on your computer.

This directory will serve as the Tomcat installation directory.

To configure Tomcat, you need to set up essential environment variables.

pg. 4 Dept of ISE , GAT


Advanced Java (ISE23404) Module-4

The JAVA_HOME variable should indicate where the Java Development Kit (JDK) is located on your system.
The CATALINA_HOME variable should point to the Tomcat installation directory. These variables are
crucial for Tomcat to locate the necessary files and execute them properly.

Step 2. Start Tomcat

After setting up the environment variables, you can start Tomcat. You can start Tomcat in different ways. It
can be run as a service or the startup scripts that are given can be used. You can also start it in manual mode
from the command line.

When Tomcat starts, it binds to a specific port, typically 8080 by default. By launching a web browser and
going to [Link] you can view the deployed applications and Tomcat server through this port.

First, copy the servlet’s class file into the following directory:
C:\apache-tomcat-10.0.7\webapps\examples\WEB-INF\classes
Next, add the servlet’s name and mapping to the [Link] file in the following directory: C:\apache-tomcat-
10.0.7\webapps\examples\WEB-INF
For instance, assuming the first example, called HelloServlet, you will add the following lines in the section
that defines the servlets:

Next, you will add the following lines to the section that defines the servlet mappings:

A Simple Servlet
To become familiar with the key servlet concepts, we will begin by building and testing a simple servlet. The
basic steps are the following:

1. Create and compile the servlet source code. Then, copy the servlet’s class file to the proper directory, and
add the servlet’s name and mappings to the proper [Link] file.
2. Start Tomcat.
3. Start a web browser and request the servlet. Let us examine each of these steps in detail.

Create and Compile the Servlet Source Code


To begin, create a file named [Link] that contains the following program:

pg. 5 Dept of ISE , GAT


Advanced Java (ISE23404) Module-4

The HelloServlet program we working will demonstrates fundamental servlet concepts, particularly the use of
the [Link] package and the structure of a servlet class

First, note that it imports the [Link] package. This package contains the classes and interfaces
required to build servlets. You will learn more about these later in this chapter. Next, the program defines
HelloServlet as a subclass of GenericServlet. The GenericServlet class provides functionality that simplifies
the creation of a servlet. For example, it provides versions of init( ) and destroy( ), which may be used as is.
You need supply only the service( ) method. Inside HelloServlet, the service( ) method (which is inherited
from GenericServlet) is overridden. This method handles requests from a client. Notice that the first argument
is a ServletRequest object. This enables the servlet to read data that is provided via the client request. The
second argument is a ServletResponse object. This enables the servlet to formulate a response for the client.
The call to setContentType( ) establishes the MIME type of the HTTP response. In this program, the MIME
type is text/html. This indicates that the browser should interpret the content as HTML source code. Next, the
getWriter( ) method obtains a PrintWriter. Anything written to this stream is sent to the client as part of the
HTTP response. Then println( ) is used to write some simple HTML source code as the HTTP response.
Compile this source code and place the [Link] file in the proper Tomcat directory as described in
the previous section. Also, add HelloServlet to the [Link] file, as described earlier.

The Servlet API

Servlets are build from two packages:


 [Link](Basic)
 [Link](Advance)
Various classes and interfaces present in these packages are:
Component Type Package

Servlet Interface [Link].*

ServletRequest Interface [Link].*

ServletResponse Interface [Link].*

GenericServlet Class [Link].*

HttpServlet Class [Link].*

HttpServletRequest Interface [Link].*

pg. 6 Dept of ISE , GAT


Advanced Java (ISE23404) Module-4

HttpServletResponse Interface [Link].*

Filter Interface [Link].*

ServletConfig Interface [Link].*

Advantages of a Java Servlet

 Servlet is faster than CGI as it doesn’t involve the creation of a new process for
every new request received.
 Servlets, as written in Java, are platform-independent.
 Removes the overhead of creating a new process for each request as Servlet
doesn’t run in a separate process. There is only a single instance that handles all
requests concurrently. This also saves the memory and allows a Servlet to easily
manage the client state.
 It is a server-side component, so Servlet inherits the security provided by the
Web server.
 The API designed for Java Servlet automatically acquires the advantages of the
Java platforms such as platform-independent and portability. In addition, it
obviously can use the wide range of APIs created on Java platforms such as JDBC
to access the database.
 Many Web servers that are suitable for personal use or low-traffic websites are
offered for free or at extremely cheap costs eg. Java servlet. However, the majority
of commercial-grade Web servers are rather expensive, with the notable exception
of Apache, which is free.

The [Link] Package

[Link]

Packages that use [Link]


The [Link] package contains a number of classes and interfaces that
describe and define the contracts between a servlet class and the runtime
[Link]
environment provided for an instance of such a class by a conforming servlet
container.
The [Link] package contains a number of classes and interfaces that
describe and define the contracts between a servlet class running under the
[Link]
HTTP protocol and the runtime environment provided for an instance of such a
class by a conforming servlet container.

Classes in [Link] used by [Link]


FilterChain
A FilterChain is an object provided by the servlet container to the developer giving a view
into the invocation chain of a filtered request for a resource.

pg. 7 Dept of ISE , GAT


Advanced Java (ISE23404) Module-4

FilterConfig
A filter configuration object used by a servlet container to pass information to a filter during
initialization.
RequestDispatcher
Defines an object that receives requests from the client and sends them to any resource (such
as a servlet, HTML file, or JSP file) on the server.
Servlet
Defines methods that all servlets must implement.
ServletConfig
A servlet configuration object used by a servlet container to pass information to a servlet
during initialization.
ServletContext
Defines a set of methods that a servlet uses to communicate with its servlet container, for
example, to get the MIME type of a file, dispatch requests, or write to a log file.
ServletContextAttributeEvent
This is the event class for notifications about changes to the attributes of the servlet context of
a web application.
ServletContextEvent
This is the event class for notifications about changes to the servlet context of a web
application.
ServletException
Defines a general exception a servlet can throw when it encounters difficulty.
ServletInputStream
Provides an input stream for reading binary data from a client request, including an
efficient readLine method for reading data one line at a time.
ServletOutputStream
Provides an output stream for sending binary data to the client.
ServletRequest
Defines an object to provide client request information to a servlet.
ServletRequestAttributeEvent
This is the event class for notifications of changes to the attributes of the servlet request in an
application.
ServletRequestEvent
Events of this kind indicate lifecycle events for a ServletRequest
ServletResponse
Defines an object to assist a servlet in sending a response to the client.

Classes in [Link] used by [Link]

GenericServlet
Defines a generic, protocol-independent servlet.

Servlet
Defines methods that all servlets must implement.

pg. 8 Dept of ISE , GAT


Advanced Java (ISE23404) Module-4

ServletConfig
A servlet configuration object used by a servlet container to pass information to a servlet during
initialization.

ServletContext
Defines a set of methods that a servlet uses to communicate with its servlet container, for
example, to get the MIME type of a file, dispatch requests, or write to a log file.

ServletException
Defines a general exception a servlet can throw when it encounters difficulty.

ServletInputStream
Provides an input stream for reading binary data from a client request, including an
efficient readLine method for reading data one line at a time.

ServletRequest
Defines an object to provide client request information to a servlet.

ServletRequestWrapper
Provides a convenient implementation of the ServletRequest interface that can be subclassed by
developers wishing to adapt the request to a Servlet.

ServletResponse
Defines an object to assist a servlet in sending a response to the client.

ServletResponseWrapper
Provides a convenient implementation of the ServletResponse interface that can be subclassed by
developers wishing to adapt the response from a Servlet.

The Servlet Interface


All servlets must implement the Servlet interface. It declares the init( ), service( ), and destroy( ) methods
that are called by the server during the life cycle of a servlet. A method is also provided that allows a servlet
to obtain any initialization parameters. The methods defined by Servlet are shown in Table [Link] init( ),
service( ), and destroy( ) methods are the life cycle methods of the servlet. These are invoked by the server.
The getServletConfig( ) method is called by the servlet to obtain initialization parameters. A servlet developer
overrides the getServletInfo( ) method to provide a string with useful information (for example, the version
number). This method is also invoked by the server.

Methods Description
void destroy( ) Called when the servlet is unloaded.

ServletConfig getServletConfig( ) Returns a ServletConfig object that contains any


initialization parameters.

pg. 9 Dept of ISE , GAT


Advanced Java (ISE23404) Module-4

String getServletInfo( ) Returns a string describing the servlet.

void init(ServletConfig sc)0020throws Called when the servlet is initialized. Initialization


ServletException parameters for the servlet can be obtained from sc. A
ServletException should be thrown if the servlet cannot
be initialized.
void service(ServletRequest req, ServletResponse res) Called to process a request from a client. The request from
throws ServletException, IOException the client can be read from req. The response to the client
can be written to res. An exception is generated if a
servlet or IO problem occurs.

Reading Servlet Parameters

The ServletRequest interface includes methods that allow you to read the names and values of parameters
that are included in a client request. We will develop a servlet that illustrates their use. The example contains
two files. A web page is defined in [Link], and a servlet is defined in
[Link]. The HTML source code for [Link] is shown in the following
listing. It defines a table that contains two labels and two text fields. One of the labels is Employee and the
other is Phone. There is also a submit button. Notice that the action parameter of the form tag specifies a URL.
The URL identifies the servlet to process the HTTP POST request.

<html>
<body>
<center>
<form name="Form1"
method="post"
action="[Link]
servlet/PostParametersServlet">
<table>
<tr>
<td><B>Employee</td>
<td><input type=textbox name="e" size="25" value=""></td>
</tr>
<tr>
<td><B>Phone</td>
<td><input type=textbox name="p" size="25" value=""></td>
</tr>
</table>
<input type=submit value="Submit">
</body>
</html>

The source code for [Link] is shown in the following listing. The service( ) method is
overridden to process client requests. The getParameterNames( ) method returns an enumeration of the
parameter names. These are processed in a loop. You can see that the parameter name and value are output
to the client. The parameter value is obtained via the getParameter( ) method.

import [Link].*;
import [Link].*;
import [Link].*;
public class PostParametersServlet
extends GenericServlet {
public void service(ServletRequest request,
ServletResponse response)
throws ServletException, IOException {
// Get print writer.
PrintWriter pw = [Link]();
// Get enumeration of parameter names.
Enumeration<String> e = [Link]();
// Display parameter names and values.

pg. 10 Dept of ISE , GAT


Advanced Java (ISE23404) Module-4

while([Link]()) {
String pname = [Link]();
[Link](pname + " = ");
String pvalue = [Link](pname);
[Link](pvalue);
}
[Link]();
}
}
Compile the servlet. Next, copy it to the appropriate directory, and update the [Link] file, as previously
described. Then, perform these steps to test this example:
1. Start Tomcat (if it is not already running).
2. Display the web page in a browser.
3. Enter an employee name and phone number in the text fields.
4. Submit the web page.
After following these steps, the browser will display a response that is dynamically generated by the servlet.

The [Link] Package

The preceding examples have used the classes and interfaces defined in [Link], such as
ServletRequest, ServletResponse, and GenericServlet, to illustrate the basic functionality of servlets.
However, when working with HTTP, you will normally use the interfaces and classes in [Link].
As you will see, its functionality makes it easy to build servlets that work with HTTP requests and responses.
The following table summarizes the interfaces used in this chapter:

Interface Description

HttpServletRequest Enables servlets to read data from an HTTP request.


HttpServletResponse Enables servlets to write data to an HTTP response.
HttpSession Allows session data to be read and written.

The following table summarizes the classes used in this chapter. The most important of these is HttpServlet.
Servlet developers typically extend this class in order to process HTTP requests.

Class Description
Cookies Allows state information to be stored on a client machine.
HttpServlet Provides methods to handle HTTP requests and responses..

The HttpServletRequest Interface


The HttpServletRequest interface enables a servlet to obtain information about a client request. Several of
its methods are shown in Table
The HttpServletResponse Interface

The HttpServletResponse interface enables a servlet to formulate an HTTP response to a client. Several constants are
defined. These correspond to the different status codes that can be assigned to an HTTP response. For example, SC_OK
indicates that the HTTP request

pg. 11 Dept of ISE , GAT


Advanced Java (ISE23404) Module-4

Method Description

String getAuthType( ) Returns authentication scheme.


Cookie[ ] getCookies( ) Returns an array of the cookies in this request.
long getDateHeader(String field) Returns the value of the date header field named field.
String getHeader(String field) Returns the value of the header field named field.
Enumeration<String> Returns an enumeration of the header names.
getHeaderNames( )
int getIntHeader(String field) Returns the int equivalent of the header field named field.
String getMethod( ) Returns the HTTP method for this request.
String getPathInfo( ) Returns any path information that is located after the
servlet path and before a query string of the URL.
String getPathTranslated( ) Returns any path information that is located after the
servlet path and before a query string of the URL after
translating it to a real path.
String getQueryString( ) Returns any query string in the URL.
String getRemoteUser( ) Returns the name of the user who issued this request.
String getRequestedSessionId( ) Returns the ID of the session.
String getRequestURI( ) Returns the URI.
Various Methods Defined by HttpServletRequest

The HttpSession Interface

The HttpSession interface enables a servlet to read and write the state information that is associated with an
HTTP session. All of these methods throw an IllegalStateException if the session has already been invalidated.

Method Description

void addCookie(Cookie cookie) Adds cookie to the HTTP response


boolean containsHeader(String field) Returns true if the HTTP response header contains
a field named field.
String encodeURL(String url) Determines if the session ID must be encoded
in the URL identified as url. If so, returns the
modified version of url. Otherwise, returns url. All
URLs generated by a servlet should be processed
by this method.
String encodeRedirectURL(String url) Determines if the session ID must be encoded
in the URL identified as url. If so, returns the
modified version of url. Otherwise, returns url.
All URLs passed to sendRedirect( ) should be
processed by this method.
void sendError(int c) Sends the error code c to the client.
throws IOException
void sendError(int c, String s) Sends the error code c and message s to the client.
throws IOException
void sendRedirect(String url) Redirects the client to url.
throws IOException
void setDateHeader(String field, long msec) Adds field to the header with date value equal to msec
(milliseconds since midnight, January 1, 1970, GMT).
Various Methods Defined by HttpServletResponse

pg. 12 Dept of ISE , GAT


Advanced Java (ISE23404) Module-4

Handling HTTP Requests and Responses

The HttpServlet class provides specialized methods that handle the various types of HTTP requests. A servlet
developer typically overrides one of these methods. These methods are doDelete( ), doGet( ), doHead( ),
doOptions( ), doPost( ), doPut( ), and doTrace( ). A complete description of the different types of HTTP
requests is beyond the scope of this book. However, the GET and POST requests are commonly used when
handling form input. Therefore, this section presents examples of these cases.

Handling HTTP GET Requests

We will develop a servlet that handles an HTTP GET request. The servlet is invoked when a form on a web
page is submitted. The example contains two files. A web page is defined in [Link], and a servlet is
defined in [Link]. The HTML source code for [Link] is shown in the following
listing. It defines a form that contains a select element and a submit button. Notice that the action parameter
of the form tag specifies a URL. The URL identifies a servlet to process the HTTP GET request

<html>
<body>
<center>
<form name="Form1"
action="[Link]
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>

The source code for [Link] is shown in the following listing. The doGet( ) method is
overridden to process any HTTP GET requests that are sent to this servlet. It uses the getParameter( ) method
of HttpServletRequest to obtain the selection that was made by the user. A response is then formulated.
import [Link].*;
import [Link].*;
import [Link].*;
public class ColorGetServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String color = [Link]("color");
[Link]("text/html");
PrintWriter pw = [Link]();
[Link]("<B>The selected color is: ");
[Link](color);
[Link]();
}

pg. 13 Dept of ISE , GAT


Advanced Java (ISE23404) Module-4

Compile the servlet. Next, copy it to the appropriate directory, and update the [Link] file, as previously
described. Then, perform these steps to test this example:
1. Start Tomcat, if it is not already running.
2. Display the web page in a browser.
3. Select a color.
4. Submit the web page.
After completing these steps, the browser will display the response that is dynamically
generated by the servlet.
One other point: Parameters for an HTTP GET request are included as part of the URL that is sent to the
web server. Assume that the user selects the red option and submits the form. The URL sent from the
browser to the server is
[Link]
The characters to the right of the question mark are known as the query string.

Handling HTTP POST Requests

Here we will develop a servlet that handles an HTTP POST request. The servlet is invoked when a form on a
web page is submitted. The example contains two files. A web page is defined in [Link], and a
servlet is defined in [Link]. The HTML source code for [Link] is shown in the
following listing. It is identical to [Link] except that the method parameter for the form tag
explicitly specifies that the POST method should be used, and the action parameter for the form tag specifies
a different servlet.

<html>
<body>
<center>
<form name="Form1"
method="post"
action="[Link]
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>

The source code for [Link] is shown in the following listing. The doPost( ) method is
overridden to process any HTTP POST requests that are sent to this servlet. It uses the getParameter( )
method of HttpServletRequest to obtain the selection that was made by the user. A response is then
formulated.
import [Link].*;
import [Link].*;
import [Link].*;
public class ColorPostServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String color = [Link]("color");
[Link]("text/html");
PrintWriter pw = [Link]();
[Link]("<B>The selected color is: ");
[Link](color);

pg. 14 Dept of ISE , GAT


Advanced Java (ISE23404) Module-4

[Link]();
}
}

Compile the servlet and perform the same steps as described in the previous section to test it.

Using Cookies

Now, let’s develop a servlet that illustrates how to use cookies. The servlet is invoked when a form on a web
page is submitted. The example contains three files as summarized here:

File Description

[Link] Allows a user to specify a value for the cookie named


MyCookie
[Link] Processes the submission of [Link].
[Link] Displays cookie values.

The HTML source code for [Link] is shown in the following listing. This page contains a text field
in which a value can be entered. There is also a submit button on the page. When this button is pressed, the
value in the text field is sent to AddCookieServlet via an HTTP POST request.

<html>
<body>
<center>
<form name="Form1"
method="post"
action="[Link]
<B>Enter a value for MyCookie:</B>
<input type=textbox name="data" size=25 value="">
<input type=submit value="Submit">
</form>
</body>
</html>
The source code for [Link] is shown in the following listing. It gets the value of the
parameter named "data". It then creates a Cookie object that has the name "MyCookie" and contains the value
of the "data" parameter. The cookie is then added to the header of the HTTP response via the addCookie( )
method. A feedback message is then written to the browser.

import [Link].*;
import [Link].*;
import [Link].*;
public class AddCookieServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Get parameter from HTTP request.
String data = [Link]("data");
// Create cookie.
Cookie cookie = new Cookie("MyCookie", data);
// Add cookie to HTTP response.
[Link](cookie);
// Write output to browser.
[Link]("text/html");
PrintWriter pw = [Link]();
[Link]("<B>MyCookie has been set to");
[Link](data);
[Link]();
}
}

pg. 15 Dept of ISE , GAT


Advanced Java (ISE23404) Module-4

The source code for [Link] is shown in the following listing. It invokes the getCookies( )
method to read any cookies that are included in the HTTP GET request. The names and values of these cookies
are then written to the HTTP response. Observe that the getName( ) and getValue( ) methods are called to
obtain this information.

import [Link].*;
import [Link].*;
import [Link].*;
public class GetCookiesServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Get cookies from header of HTTP request.
Cookie[] cookies = [Link]();
// Display these cookies.
[Link]("text/html");
PrintWriter pw = [Link]();
[Link]("<B>");
for(int i = 0; i < [Link]; i++) {
String name = cookies[i].getName();
String value = cookies[i].getValue();
[Link]("name = " + name +
"; value = " + value);
}
[Link]();
}
}

Compile the servlets. Next, copy them to the appropriate directory, and update the [Link] file, as previously
described. Then, perform these steps to test this example:
1. Start Tomcat, if it is not already running.
2. Display [Link] in a browser.
3. Enter a value for MyCookie.
4. Submit the web page.
After completing these steps, you will observe that a feedback message is displayed by the browser.
Next, request the following URL via the browser:
[Link]
Observe that the name and value of the cookie are displayed in the browser.
In this example, an expiration date is not explicitly assigned to the cookie via the setMaxAge( ) method of
Cookie. Therefore, the cookie expires when the browser session ends. You can experiment by using
setMaxAge( ) and observe that the cookie is then saved on the client machine

Session Tracking
HTTP is a stateless protocol. Each request is independent of the previous one. However, in some applications,
it is necessary to save state information so that information can be collected from several interactions between
a browser and a server. Sessions provide such a mechanism.
A session can be created via the getSession( ) method of HttpServletRequest. An HttpSession object is
returned. This object can store a set of bindings that associate names with objects. The setAttribute( ),
getAttribute( ), getAttributeNames( ), and removeAttribute( ) methods of HttpSession manage these
bindings. Session state is shared by all servlets that are associated with a client.
The following servlet illustrates how to use session state. The getSession( ) method gets the current session.
A new session is created if one does not already exist. The getAttribute( ) method is called to obtain the object
that is bound to the name "date". That object is a Date object that encapsulates the date and time when this
page was last accessed. (Of course, there is no such binding when the page is first accessed.) A Date object
encapsulating the current date and time is then created. The setAttribute( ) method is called to bind the name
"date"0020to this object.

pg. 16 Dept of ISE , GAT


Advanced Java (ISE23404) Module-4

import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class DateServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Get the HttpSession object.
HttpSession hs = [Link](true);
// Get writer.
[Link]("text/html");
PrintWriter pw = [Link]();
[Link]("<B>");
// Display date/time of last access.
Date date = (Date)[Link]("date");
if(date != null) {
[Link]("Last access: " + date + "<br>");
}
// Display current date/time.
date = new Date();
[Link]("date", date);
[Link]("Current date: " + date);
}
}

When you first request this servlet, the browser displays one line with the current date and time information. On
subsequent invocations, two lines are displayed. The first line shows the date and time when the servlet was last
accessed. The second line shows the current date and time.

JSP(JavaServer Pages)

JavaServer Pages (JSP) is a technology for developing web pages that support dynamic content
which helps developers insert java code in HTML pages by making use of special JSP tags.

Using JSP, you can collect input from users through web page forms, present records from a
database or another source, and create web pages dynamically.

Advantages of JSP:

vs. Pure Servlets: It is more convenient to write (and to modify!) regular HTML than to
have plenty of println statements that generate the HTML.

JSP Processing:
The following steps explain how the web server creates the web page using JSP:

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

 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.

 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 that implements the corresponding
dynamic behavior of the page.

pg. 17 Dept of ISE , GAT


Advanced Java (ISE23404) Module-4

 The JSP engine compiles the servlet into an executable class and forwards the original
request to a servlet engine.

 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, which the servlet
engine passes to the web server inside an HTTP response.

 The web server forwards the HTTP response to your browser in terms of static HTML
content.

 Finally web browser handles the dynamically generated HTML page inside the HTTP
response exactly as if it were a static page.

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

pg. 18 Dept of ISE , GAT


Advanced Java (ISE23404) Module-4

pg. 19 Dept of ISE , GAT


Advanced Java (ISE23404) Module-4

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)

{
// Service handling code...

pg. 20 Dept of ISE , GAT


Advanced Java (ISE23404) Module-4

The _jspService() method of a JSP is invoked once per a request and 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 ie. 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.

JSP Elements :
1. JSP Comments
2. JSP Scriptlets
3. JSP Expression
4. JSP Directives
5. JSP Declaration

1. JSP Comments
Since JSP is built on top of HTML, we can write comments in JSP file like html comments
as

<-- This is HTML Comment -->

pg. 21 Dept of ISE , GAT


Advanced Java (ISE23404) Module-4

These comments are sent to the client and we can look it with view source option of
browsers.

We can put comments in JSP files as:

<%-- This is JSP Comment--%>

This comment is suitable for developers to provide code level comments because these are
not sent in the client response.

2. JSP Scriptlets
Scriptlet tags are the easiest way to put java code in a JSP page. A scriptlet tag starts with <%
and ends with %>.

Any code written inside the scriptlet tags go into the _jspService()method. For example:

<%

Date d = new Date(); [Link]("Current

Date="+d);

%>

3. JSP Expression
Since most of the times we print dynamic data in JSP page
using [Link]() method, there is a shortcut to do this through JSP Expressions. JSP
Expression starts with <%= and ends with %>.

<% [Link]("Pankaj"); %>can be written using JSP Expression as


<%= "Pankaj" %>

Notice that anything between <%= %>is sent as parameter


to [Link]()method. Also notice that scriptlets can contain multiple java statements and
always ends with semicolon (;) but expression doesn’t end with semicolon.

pg. 22 Dept of ISE , GAT


Advanced Java (ISE23404) Module-4

4. JSP Directives
JSP Directives are used to give special instructions to the container while JSP page is getting
translated to servlet source code. JSP directives starts
with <%@and ends with %>

For example, in above JSP Example, I am using page directive to to instruct container JSP
translator to import the Date class.

5. JSP Declaration
JSP Declarations are used to declare member methods and variables of servlet class. JSP
Declarations starts with <%! and ends with %>.

For example we can create an int variable in JSP at class level as <%! public static int
count=0; %>

JSP Implicit Objects:

JSP supports nine automatically defined variables, which are also called implicit objects. These
variables are:

Objects Description

This is the HttpServletRequest object associated with the


request
request.

This is the HttpServletResponse object associated with the


response
response to the client.

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

session This is the HttpSession object associated with the request.

This is the ServletContext object associated with application


application context.

config This is the ServletConfig object associated with the page.

pg. 23 Dept of ISE , GAT


Advanced Java (ISE23404) Module-4

This encapsulates use of server-specific features like higher


pageContext
performance JspWriters.

This is simply a synonym for this, and is used to call the


page methods defined by the translated servlet class.

The Exception object allows the exception data to be accessed


Exception
by designated JSP.

JSP Directives:

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:

Directive Description

Defines page-dependent attributes, such as scripting language,


<%@ page ... %>
error page, and buffering requirements.

<%@ include ... %> Includes a file during the translation phase.

Declares a tag library, containing custom actions, used in the


<%@ taglib ... %>
page

pg. 24 Dept of ISE , GAT


Advanced Java (ISE23404) Module-4

JSP Action Tags:


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 and there are following JSP actions
available:

Syntax Purpose

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

jsp:useBean Finds or instantiates a JavaBean

jsp:setProperty Sets the property of a JavaBean

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

jsp:forward Forwards the requester to a new page

Generates browser-specific code that makes an OBJECT or


jsp:plugin EMBED tag for the Java plugin

jsp:element Defines XML elements dynamically.

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

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

jsp:text Use to write template text in JSP pages and documents.

pg. 25 Dept of ISE , GAT


To give an example for a JSP code, first we are going to print the text "Hello Hiox". Try the the
following syntax code.

Example :

<html>

<body>

<! -- This is the JSP file-->

<%

[Link] ("Hello HIOX");

%>

Result</body>
:
</html>
Hello HIOX

JSP Architecture
JSP architecture gives a high-level view of the working of JSP. JSP architecture is a 3 tier architecture.
It has a Client, Web Server, and Database. The client is the web browser or application on the user side.
Web Server uses a JSP Engine i.e; a container that processes JSP. For example, Apache Tomcat has a built-
in JSP Engine. JSP Engine intercepts the request for JSP and provides the runtime environment for the
understanding and processing of JSP files. It reads, parses, build Java Servlet, Compiles and Executes
Java code, and returns the HTML page to the client. The webserver has access to the Database. The
following diagram shows the architecture of JSP.

Now let us discuss JSP which stands for Java Server Pages. It is a server-side technology. It is used for
creating web applications. It is used to create dynamic web content. In this JSP tags are used to insert JAVA
code into HTML pages. It is an advanced version of Servlet Technology. It is a Web-based technology that
helps us to create dynamic and platform-independent web pages. In this, Java code can be inserted in HTML/
XML pages or both. JSP is first converted into a servlet by JSP container before processing the client’s
request. JSP Processing is illustrated and discussed in sequential steps prior to which a pictorial media is

pg. 26 Dept of ISE , GAT


provided as a handful pick to understand the JSP processing better which is as follows:

pg. 27 Dept of ISE , GAT


Step 1: The client navigates to a file ending with the .jsp extension and the browser initiates an HTTP
request to the webserver. For example, the user enters the login details and submits the button. The browser
requests a [Link] page from the webserver.
Step 2: If the compiled version of JSP exists in the web server, it returns the file. Otherwise, the request is
forwarded to the JSP Engine. This is done by recognizing the URL ending with .jsp extension.
Step 3: The JSP Engine loads the JSP file and translates the JSP to Servlet(Java code). This is done by
converting all the template text into println() statements and JSP elements to Java code. This process is
called translation.
Step 4: The JSP engine compiles the Servlet to an executable .class file. It is forwarded to the Servlet
engine. This process is called compilation or request processing phase.
Step 5: The .class file is executed by the Servlet engine which is a part of the Web Server. The output is
an HTML file. The Servlet engine passes the output as an HTTP response to the webserver.
Step 6: The web server forwards the HTML file to the client’s browser.

What is JSP?
In Java, JSP stands for Java Server Pages. It is a server-side technology which is used for creating web
applications. It is used to create dynamic web content. JSP consists of both HTML tags and JSP tags. In this, JSP
tags are used to insert JAVA code into HTML pages. It is an advanced version of Servlet Technology i.e. a
web-based technology that helps us to create dynamic and platform-independent web pages. In this, Java code
can be inserted in HTML/ XML pages or both. JSP is first converted into a servlet by the JSP container before
processing the client’s request. JSP has various features like JSP Expressions, JSP tags, JSP Expression Language,
etc.
How JSP more advantageous than Servlet?
 They are easy to maintain.
 No recompilation or redeployment is required.
 Less coding is required in JSP.
 JSP has access to the entire API of JAVA.
 JSP are extended version of Servlet.
Features of JSP
 Coding in JSP is easy : As it is just adding JAVA code to HTML/XML.
 Reduction in the length of Code : In JSP we use action tags, custom tags etc.
 Connection to Database is easier : It is easier to connect website to database and allows to read or
write data easily to the database.

pg. 28 Dept of ISE , GAT


 Make Interactive websites : In this we can create dynamic web pages which helps user to interact in
real time environment.
 Portable, Powerful, flexible and easy to maintain : as these are browser and server independent.
 No Redeployment and No Re-Compilation : It is dynamic, secure and platform independent so no
need to re-compilation.
 Extension to Servlet : as it has all features of servlets, implicit objects and custom tags
1. Declaration Tag : It is used to declare variables.
2. Java Scriplets : It allows us to add any number of JAVA code, variables and expressions.
3. JSP Expression : It evaluates and convert the expression to a string.
4. JAVA Comments : It contains the text that is added for information which has to be
ignored.
 Create html page from where request will be sent to server eg [Link].
 To handle to request of user next is to create .jsp file Eg. [Link]
 Create project folder structure.
 Create XML file eg [Link].
 Create WAR file.
 Start Tomcat
 Run Application
5. It does not require advanced knowledge of JAVA
6. It is capable of handling exceptions
7. Easy to use and learn
8. It contains tags which are easy to use and understand
9. Implicit objects are there which reduces the length of code
10. It is suitable for both JAVA and non JAVA programmer
11. Difficult to debug for errors.
12. First time access leads to wastage of time
13. It’s output is HTML which lacks features.

Variables and Objects


Variables and objects are managed within specific scopes (request, session, application) to control their lifecycle
and accessibility. Understanding these scopes is crucial for managing data and state across multiple requests and
users.
Java Server Pages (JSP) uses variables and objects to store and manage data dynamically. These can be
categorized
into implicit objects, scriptlet variables, and JSP scopes.

JSP Implicit Objects

JSP provides several predefined objects that developers can use without explicitly declaring them. These
objects help in handling HTTP requests, responses, sessions, and application-wide data.

List of JSP Implicit Objects

Object Type Description

request HttpServletRequest Contains data from the client's


request.
response HttpServletResponse Represents the response sent to the
client.

pg. 29 Dept of ISE , GAT


session HttpSession Stores user session data across
multiple requests.
application ServletContext Shares data across the entire web
application.
out JspWriter Outputs content to the client.
config ServletConfig Retrieves servlet configuration
details.
pageContext PageContext Provides access to page attributes
and other JSP objects.

JSP Variables

JSP allows variables to be declared in different ways:

a) Scriptlet Variables (<% %>)

 These are declared within scriptlets and follow Java syntax.


 Example:

<%
int count = 10;
String message = "Hello, JSP!";
%>
b)Declaration Variables (<%! %>)

 These are declared at the class level and persist across requests.
 Example:

<%!

int counter = 0;

%>

c)Expression Variables (<%= %>)

 Used to display values in JSP pages.


 Example:

<%= "Welcome, " + [Link]("user") %>

JSP Variable Scopes

JSP variables can exist in different scopes, which define how long they remain accessible.

a) Page Scope ([Link]/getAttribute)

 The variable is accessible only in the current JSP page.

pg. 30 Dept of ISE , GAT


 Example:

jsp
CopyEdit
<%
[Link]("username", "JohnDoe");
%>
b) Request Scope ([Link]/getAttribute)

 The variable persists throughout a single request, useful for passing data between JSP pages.
 Example:

jsp
CopyEdit
<%
[Link]("userRole", "admin");
%>
c) Session Scope ([Link]/getAttribute)

 The variable is available as long as the user session is active.


 Example:

jsp
CopyEdit
<%
[Link]("loggedInUser", "Alice");
%>
d) Application Scope ([Link]/getAttribute)

 The variable is shared across the entire application and is accessible by all users.
 Example:

jsp
CopyEdit
<%
[Link]("appName", "MyWebApp");
%>

Example: Using Variables and Objects in JSP


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<html>
<head><title>JSP Variables and Objects</title></head>
<body>

<%
String userName = "John"; // Scriptlet variable
[Link]("userRole", "Admin"); // Request scope variable
[Link]("userEmail", "john@[Link]"); // Session scope variable
%>

<p>Welcome, <%= userName %></p>


<p>Your Role: <%= [Link]("userRole") %></p>
<p>Your Email: <%= [Link]("userEmail") %></p>

</body>
</html>

pg. 31 Dept of ISE , GAT

You might also like