0% found this document useful (0 votes)
8 views51 pages

Chapter 4 - Servlets

This chapter provides an overview of server-side technology, specifically focusing on Java servlet technology, its advantages over CGI, and the basic execution philosophy of servlets. It covers the installation and configuration of the Tomcat servlet engine, the lifecycle of servlets, and important concepts like session tracking and request dispatching. Additionally, it explains the differences between various HTTP request methods and the functionalities of the RequestDispatcher and sendRedirect methods.

Uploaded by

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

Chapter 4 - Servlets

This chapter provides an overview of server-side technology, specifically focusing on Java servlet technology, its advantages over CGI, and the basic execution philosophy of servlets. It covers the installation and configuration of the Tomcat servlet engine, the lifecycle of servlets, and important concepts like session tracking and request dispatching. Additionally, it explains the differences between various HTTP request methods and the functionalities of the RequestDispatcher and sendRedirect methods.

Uploaded by

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

CHAPTER FOUR

02/06/25 COMPILED BY: ZIYAD A. 1


At the end of this chapter, you will be able to:

 get an idea about server-side technology

 understand the advantages of Java servlet technology over


other similar technologies

 get an idea about the basic execution philosophy of servlets

 understand how to write, deploy, and invoke servlets

 learn how to install and configure Tomcat servlet engine

 learn how to use important concepts such as Cookies, session


tracking, etc.

02/06/25 COMPILED BY: ZIYAD A. 2


 Web consists of billions of clients and server connected through
wires and wireless networks. The web clients make requests to web
server. The web server receives the request, finds the resources and
return the response to the client. When a server answers a request, it
usually sends some type of content to the client. The client uses web
browser to send request to the server. The server often sends response
to the browser with a set of instructions written in HTML(HyperText
Markup Language). All browsers know how to display HTML page
to the client.

02/06/25 COMPILED BY: ZIYAD A. 3


02/06/25 COMPILED BY: ZIYAD A. 4
Web Application

A website is a collection of static files(webpages) such as HTML pages,


images, graphics etc. A Web application is a web site with dynamic
functionality on the server. Google, Facebook, Twitter are examples of web
applications.

HTTP (Hypertext Transfer Protocol)

HTTP is a protocol that clients and servers use on the web to communicate.

It is similar to other internet protocols such as SMTP(Simple Mail Transfer


Protocol) and FTP(File Transfer Protocol) but there is one fundamental
difference.

02/06/25 COMPILED BY: ZIYAD A. 5


HTTP is a stateless protocol i.e HTTP supports only one request per
connection. This means that with HTTP the clients connect to the
server to send one request and then disconnects. This mechanism
allows more users to connect to a given server over a period of time.

The client sends an HTTP request and the server answers with an
HTML page to the client, using HTTP.

02/06/25 COMPILED BY: ZIYAD A. 6


Servlet technology is used to create web application (resides at server
side and generates dynamic web page).

Servlet technology is robust and scalable because of java language.


Before Servlet, CGI (Common Gateway Interface) scripting language
was popular as a server-side programming language. But there was
many disadvantages of this technology. We have discussed these
disadvantages below.

There are many interfaces and classes in the servlet API such as
Servlet,GenericServlet,HttpServlet,ServletRequest,ServletResponse
etc.

02/06/25 COMPILED BY: ZIYAD A. 7


What is a Servlet?
Servlet is a technology i.e. used to create web application.

A servlet is a compiled Java class that run server-side under the control of the Web
server.

Servlets are managed by the servlet container, or servlet engine

Servlets are called through HTML

Servlet is an API that provides many interfaces and classes including documentations.

Servlet is a class that extend the capabilities of the servers and respond to the incoming
request. It can respond to any type of requests.

Servlet is a web component that is deployed on the server to create dynamic web page.

02/06/25 COMPILED BY: ZIYAD A. 8


02/06/25 COMPILED BY: ZIYAD A. 9
Servlets receive requests and return responses, both of which are supported by
the HTTP protocol

When the Web Server receives a request that is for a servlet, the request is
passed to the servlet container
oThe container makes sure the servlet is loaded and calls it
oThe servlet call has two parameter objects, one with the request and one for
the response
oWhen the servlet is finished, the container reinitializes itself and returns
control to the Web server

Servlets are used 1) as alternatives to CGI, and 2) as alternatives to Apache


modules
02/06/25 COMPILED BY: ZIYAD A. 10
WHY ARE SERVLETS?
Web pages with dynamic content
Easy coordination between Servlets to
make Web applications
Containers support many features
Sessions, persistence, resource management
(e.g., database connections),
Static security,
File system etc.

HTTP Web
Server
Servlet
Dynamic Server

02/06/25
Tomcat = Web Server + Servlet
COMPILED BY: ZIYAD A. 11
Server
CGI technology enables the web server to call an external program
and pass HTTP request information to the external program to
process the request. For each request, it starts a new process.

02/06/25 COMPILED BY: ZIYAD A. 12


Disadvantages of CGI

There are many problems in CGI technology:

•Inefficient: new process for each request!!!


o If number of clients increases, it takes more time for sending
response.
oServlets loaded “once”!
Defines only the interface
 no supporting infrastructure (security, sessions,
persistence, etc.)

It is platform dependent
02/06/25 COMPILED BY: ZIYAD A. 13
Advantages of Servlet
There are many advantages of servlet over CGI. The web container
creates threads for handling the multiple requests to the servlet.
Threads have a lot of benefits over the Processes such as they share
a common memory area, lightweight, cost of communication
between the threads are low. The basic benefits of servlet are as
follows:
better performance: because it creates a thread for each request not
process.
Portability: because it uses java language.
Robust: Servlets are managed by JVM so no need to worry about
memory leak, garbage collection etc.
02/06/25 COMPILED BY: ZIYAD A. 14
Secure: because it uses java language..
Advantages of Servlet

02/06/25 COMPILED BY: ZIYAD A. 15


The basic terminology used in servlet are given below:
1. HTTP
2. HTTP Request Types
3. Get and Post method
4. Container
5. Web Server and Application Server
6. Content Type
7. XML
8. Deployment

02/06/25 COMPILED BY: ZIYAD A. 16


The javax.servlet and javax.servlet.http packages
represent interfaces and classes for servlet api.

The javax.servlet package contains many interfaces and


classes that are used by the servlet or web container.
These are not specific to any protocol.

The javax.servlet.http package contains interfaces and


classes that are responsible for http requests only.

02/06/25 COMPILED BY: ZIYAD A. 17


GenericServlet class
GenericServlet class implements Servlet, ServletConfig and
Serializable interfaces. It provides the implementaion of all
the methods of these interfaces except the service method.

GenericServlet class can handle any type of request so it is


protocol-independent.

You may create a generic servlet by inheriting the


GenericServlet class and providing the
implementation of the service method.
02/06/25 COMPILED BY: ZIYAD A. 18
HttpServlet class

The HttpServlet class extends the GenericServlet class and


implements Serializable interface. It provides http specific methods
such as doGet, doPost, doHead, doTrace etc.
Technically, a servlet is a program that
extends either GenericServlet or HttpServlet.

02/06/25 COMPILED BY: ZIYAD A. 19


The web container maintains the life cycle of a servlet instance.
Servlets are controlled by servers
1. A server loads and initializes the servlet

New thread created for each client.

2. The servlet handles zero or more client requests


3. The server terminates the servlet
Methods

public void init():
Called only once when servlet is being created.
Good place for set up, open Database, etc.

public void service():
Called once for each request.
In HttpServlet, it delegates requests to doGet, doPost, etc.

public void destroy():
Called when server decides to terminate the servlet.
Release resources.
02/06/25 COMPILED BY: ZIYAD A. 20
The servlet can be created by three ways:

1.By implementing Servlet interface,

2.By inheriting GenericServlet class, (or)

3.By inheriting HttpServlet class

The mostly used approach is by extending HttpServlet because it


provides http request specific method such as doGet(), doPost(),

doHead() etc.

02/06/25 COMPILED BY: ZIYAD A. 21


Most user-written servlet classes are extensions to HttpServlet
(which is an extension of GenericServlet, which implements the
Servlet Interface)
HttpServlet – an abstract class, extends GenericServlet
 Every subclass of HttpServlet MUST override at least one of the
methods of HttpServlet
 doGet*
 doPost*
 doPut*
 doDelete*
 init
 destroy
 getServletInfo
 * Called by the server
02/06/25 COMPILED BY: ZIYAD A. 22
For HTTP requests.
 HTTP requests include
 GET, conditional GET, HEAD, POST, PUT, DELETE, TRACE,
OPTIONS
 The default is GET.
Methods of HttpServlet and HTTP requests

All methods take two arguments: an HttpServletRequest object


and an HttpServletResponse object.

02/06/25 COMPILED BY: ZIYAD A.


23
 The protocol of doGet is:
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,java.io.IOException

ServletException is thrown if the GET request could not be
handled.
 The protocol of doPost is similar to doGet

 Servlet output – HTML

1. Use the setContentType method of the response


object to set the content type to text/html
response.setContentType("text/html");

2. Create a PrintWriter object with the getWriter


method of the response object
PrintWriter Out = response.getWriter();
02/06/25 COMPILED BY: ZIYAD A.
24
 javax.servlet.http.HttpServletRequest Objects
 Extends the ServletRequest
 Provide access to HTTP header data and the arguments of the
request.
 Can get values of individual parameters using the following
methods

getParameterNames method provides the names of the
parameters

getParameter method returns the value of a named
02/06/25
parameter.
COMPILED BY: ZIYAD A.
25
 HttpServletResponse Objects
 Provide two ways of returning data to the user:


getWriter method returns a PrintWriter for sending text data to
client

getOutputStream method returns a ServletOutputStream for
sending binary data to client.

Need to close the Writer or ServletOutputStream after you send
the response.
 HTTP Header Data


Must set HTTP header data before you access the Writer or
OutputStream.

HttpServletResponse interface provides methods to manipulate
the header data.

For example, the setContentType method sets the content26 type.
(This header is often the only one manuallyCOMPILED
02/06/25 set.)BY: ZIYAD A.
1. Install Apache Tomcat in your computer

2. Define environment variable JAVA_HOME


 JAVA_HOME should point to the directory containing your Java installation

 Eg. C:\Program Files\Java\jdk1.7.0_10

3. Define Environment variable CATALINA_HOME


 CATALINA_HOME should point to the directory that contains Tomcat

 Eg. C:\Program Files\Apache Software Foundation\Apache Tomcat 8.0.3

4. To start the Tomcat server, use

CATALINA_HOME\bin\startup.bat

5. To stop the Tomcat server, use

CATALINA_HOME\bin\shutdown.bat
02/06/25 COMPILED BY: ZIYAD A. 27
The RequestDispatcher interface provides the facility of dispatching the request to
another resource it may be html, servlet or jsp. This interface can also be used to include
the content of another resource also. It is one of the way of servlet collaboration.

There are two methods defined in the RequestDispatcher interface.

Methods of RequestDispatcher interface

The RequestDispatcher interface provides two methods. They are:

1. public void forward(ServletRequest request,ServletResponse response)throws


ServletException,java.io.IOException:

Forwards a request from a servlet to another resource (servlet, JSP file, or HTML
file) on the server.

02/06/25 COMPILED BY: ZIYAD A.


28
2. public void include(ServletRequest request,ServletResponse response)throws
ServletException,java.io.IOException: Includes the content of a resource (servlet, JSP
page, or HTML file) in the response.

As you see in the above figure, response of second servlet is sent to the client. Response
02/06/25 COMPILED BY: ZIYAD A.
29
As you can see in the above figure, response of second servlet is
included in the response of the first servlet that is being sent to the
client.
02/06/25 COMPILED BY: ZIYAD A.
30
How to get the object of RequestDispatcher

The getRequestDispatcher() method of ServletRequest interface


returns the object of RequestDispatcher.

Syntax:
public RequestDispatcher getRequestDispatche
r(String resource);

Example:
RequestDispatcher rd=request.getRequestDispatche
r("servlet2");
//servlet2 is the url-pattern of the second servlet

rd.forward(request, response);//
02/06/25 COMPILED BY: ZIYAD A.
method may be include or forward
SendRedirect in servlet

The sendRedirect() method of HttpServletResponse interface can


be used to redirect response to another resource, it may be servlet, jsp
or html file.

It accepts relative as well as absolute URL.

It works at client side because it uses the url bar of the browser to
make another request. So, it can work inside and outside the server

02/06/25 COMPILED BY: ZIYAD A. 32


Difference between forward() and sendRedirect() method

There are many differences between the forward() method of


RequestDispatcher and sendRedirect() method of
HttpServletResponse interface. They are given below:

forward() method sendRedirect() method

The forward() method works at server side. The sendRedirect() method works at client side.

It sends the same request and response objects to


It always sends a new request.
another servlet.

It can work within the server only. It can be used within and outside the server.

Example:
request.getRequestDispacher("servlet2").forward Example: response.sendRedirect("servlet2");
(request,response);
02/06/25 COMPILED BY: ZIYAD A.
33
Syntax of sendRedirect() method

public void sendRedirect(String URL)throws IOException;

Example
response.sendRedirect("http://www.google.com");

02/06/25 COMPILED BY: ZIYAD A. 34


What is a Session?

Session simply means a particular interval of time.

Session Tracking is a way to maintain state (data) of an user. It is


also known as session management in servlet.

Http protocol is a stateless so we need to maintain state using


session tracking techniques. Each time user requests to the server,
server treats the request as the new request. So we need to maintain
the state of an user to recognize to particular user.

02/06/25 COMPILED BY: ZIYAD A.


35
HTTP is stateless that means each request is considered as the new
request. It is shown in the figure given below:

Why use Session Tracking?

To recognize the user :It is used to recognize the particular user.


02/06/25 COMPILED BY: ZIYAD A.
36
Session Tracking Techniques

There are four techniques used in Session tracking:

1.Cookies

2.Hidden Form Field

3.URL Rewriting

4.HttpSession

02/06/25 COMPILED BY: ZIYAD A.


37
1. Cookie

A cookie is a small piece of information that is persisted between the multiple


client requests.

A cookie has a name, a single value, and optional attributes such as a


comment, path and domain qualifiers, a maximum age, and a version number.

How Cookie works

By default, each request is considered as a new request. In cookies technique,


we add cookie with response from the servlet. So cookie is stored in the cache
of the browser. After that if request is sent by the user, cookie is added with
request by default. Thus, we recognize the user as the old user.

02/06/25 COMPILED BY: ZIYAD A. 38


1. Cookie

Types of Cookie

There are 2 types of cookies in servlets.

1. Non-persistent cookie

2. Persistent cookie
02/06/25 COMPILED BY: ZIYAD A. 39
1. Cookie

Non-persistent cookie

It is valid for single session only. It is removed each time when user closes
the browser.

Persistent cookie

It is valid for multiple session . It is not removed each time when user
closes the browser. It is removed only if user logout or signout.

02/06/25 COMPILED BY: ZIYAD A. 40


Advantage of Cookies

1.Simplest technique of maintaining the state.

2.Cookies are maintained at client side.

Disadvantage of Cookies

1.It will not work if cookie is disabled from the browser.

2.Only textual information can be set in Cookie object.


Note: Gmail uses cookie technique for login. If you disable the
cookie, gmail won't work.

02/06/25 COMPILED BY: ZIYAD A. 41


Cookie class

javax.servlet.http.Cookie class provides the functionality of using


cookies. It provides a lot of useful methods for cookies.

Constructor of Cookie class

Constructor Description

Cookie() constructs a cookie.

Cookie(String name, String constructs a cookie with a


value) specified name and value

02/06/25 COMPILED BY: ZIYAD A. 42


2. Hidden Form Field

In case of Hidden Form Field a hidden (invisible) textfield is used for


maintaining the state of an user.

In such case, we store the information in the hidden field and get it from
another servlet. This approach is better if we have to submit form in all the
pages and we don't want to depend on the browser.

Let's see the code to store value in hidden field.


<input type="hidden" name="uname" value=“admin">

Here, uname is the hidden field name and admin is the hidden field value.

02/06/25 COMPILED BY: ZIYAD A. 43


2. Hidden Form Field

Advantage of Hidden Form Field

It will always work whether cookie is disabled or not.

Disadvantage of Hidden Form Field:


1.It is maintained at server side.
2.Extra form submission is required on each pages.
3.Only textual information can be used.

02/06/25 COMPILED BY: ZIYAD A. 44


3) URL Rewriting

In URL rewriting, we append a token or identifier to the URL of the


next Servlet or the next resource. We can send parameter name/value
pairs using the following format:
url?
A name name1=value1&name2=value2&
and a value is separated using an equal = sign, a parameter
??
name/value pair is separated from another parameter using the
ampersand(&). When the user clicks the hyperlink, the parameter
name/value pairs will be passed to the server. From a Servlet, we can
use getParameter() method to obtain a parameter value.

02/06/25 COMPILED BY: ZIYAD A. 45


3) URL Rewriting

Advantage of URL Rewriting

It will always work whether cookie is disabled or not (browser


independent).

Extra form submission is not required on each pages.

Disadvantage of URL Rewriting

It will work only with links.

It can send Only textual information.

02/06/25 COMPILED BY: ZIYAD A. 46


4) HttpSession interface

In such case, container creates a session id for each user. The container
uses this id to identify the particular user.

An object of HttpSession can be used to perform two tasks:

1.bind objects

2.view and manipulate information about a session, such as the


session identifier, creation time, and last accessed time.

02/06/25 COMPILED BY: ZIYAD A. 47


4) HttpSession interface

02/06/25 COMPILED BY: ZIYAD A. 48


4) HttpSession interface

How to get the HttpSession object ?

The HttpServletRequest interface provides two methods to get the object


of HttpSession:

1.public HttpSession getSession():Returns the current session associated


with this request, or if the request does not have a session, creates one.

2.public HttpSession getSession(boolean create):Returns the current


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

02/06/25 COMPILED BY: ZIYAD A. 49


4) HttpSession interface

Commonly used methods of HttpSession interface

public String getId():Returns a string containing the unique identifier value.

public long getCreationTime():Returns the time when this session was created,
measured in milliseconds since midnight January 1, 1970 GMT.

public long getLastAccessedTime():Returns the last time the client sent a request
associated with this session, as the number of milliseconds since midnight January 1,
1970 GMT.

public void invalidate():Invalidates this session then unbinds any objects bound to
it.

02/06/25 COMPILED BY: ZIYAD A. 50


51

You might also like