Sunteți pe pagina 1din 95

Unit- 3

Servlet

1/16/17

Servlet API and Overview


Servlet Model: Overview of Servlet, Servlet Life
Cycle, HTTP Methods
Structure and Deployment descriptor
ServletContext and ServletConfig interface,
Attributes in Servlet, Request Dispatcher
interface
The Filter API: Filter, FilterChain, Filter Config
Cookies and Session Management:
Understanding state and session, Understanding
Session Timeout and Session Tracking, URL
Rewriting

CONTENTS
CGI

of Web Based Applications

1/16/17

Need
CGI

vs Servlet
What is Servlet
Servlet Life Cycle

Need of Web Based Applications?


access

1/16/17

Universal

Everyone already has a browser installed.


Any computer on the network can access content

Automatic updates

Content

comes from server, so is never out of date

1/16/17

1/16/17

1/16/17

1/16/17

1/16/17

1/16/17

10

1/16/17

11

1/16/17

12

CGI Scripts
CGI

stands for Common Gateway Interface


Common Gateway Interface(CGI) is a standard
environment for web servers to interface with executable
programs installed on a server that generate web pages
dynamically.
Client sends a request to server
Server starts a CGI script
Script computes a result for server
and quits
Server returns response to client

client
client

server
script

Another client sends a request


Server starts the CGI script again
Etc.
13

1/16/17

14

1/16/17

15

1/16/17

16

Servlet
servlet is a server side platform independent,
dynamic and multithread java program, which
runs in the context of server for extending the
functionality of server. When multiple users
make a request to the same servlet then all
requests will be processed by the container by
creating multiple threads for the same servlet. In
order to deal with these servlet programming, we
must import

1/16/17

17

javax.servlet.*;
javax.servlet.http.*; into our java program.
javax.servlet.Servletis one of pre-defined top mostinterface,
which is containinglife cyclemethods[init(),service(),destroy()
javax.servlet.GenericServletis one of the predefined abstract class
which is implementingjavax.servlet.Servletinterface, this
GenericServlet class is used for developing protocol independent
applications [ But in real time we will use protocol dependent
applications only, so GenericServlet wont be appeared in real time
]
Javax.servlet.http.HttpServletis sub class of GenericServlet used
for developing protocol dependent application [HTTPprotocol ]

1/16/17

18

What is a Servlet?
Servlet

1/16/17

is a web component that is deployed on the server


to create dynamic web page.
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 technology i.e. used to create web
application.
Servlet is an API that provides many interfaces and
classes including documentations.
Servlet is an interface that must be implemented for
creating any servlet.
A servlet is a small, pluggable extension to a
server that enhances the servers functionality.

19

1/16/17

20

1/16/17

21

Servlets

servlet is like an applet, but on the server side

Client sends a request to server


Server starts a servlet
Servlet computes a result for
server and does not quit
Server returns response to client

client
client

server
servlet

Another client sends a request


Server calls the servlet again
Etc.
22

Servlets vs. CGI scripts


Advantages:

a servlet doesnt require creating a separate


process each time
A servlet stays in memory, so it doesnt have to be
reloaded each time
There is only one instance handling multiple requests,
not a separate instance for every request
Untrusted servlets can be run in a sandbox

1/16/17

Running

Disadvantage:
Less

choice of languages (CGI scripts can be in any


language)

23

1/16/17

Advantage
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.
Secure: because it uses java language..

24

Server
It

is a running program or software that provides services.


There are two types of servers:
Server

Web Server
Web server contains only web or servlet container. It can be used for
servlet, jsp, struts, jsf etc. It can't be used for EJB(Enterprise java beans).
Example of Web Servers are: Apache Tomcat and Resin.
Application Server
Application server contains Web and EJB containers. It can be used for
servlet, jsp, struts, jsf, ejb etc.
Application Server/ EJB container provides most of the system
level services like transaction handling, logging, load balancing,
persistence mechanism, exception handling and so on. Developer
has to focus only on business logic of the application.
EJB container manages life cycle of ejb instances thus developer
needs not to worry about when to create/delete ejb objects.
Example of Application Servers are:
JBoss Open-source server from JBoss community.
Glassfish provided by Sun Microsystem. Now acquired by Oracle.

1/16/17

Web Server
Application

25

Servres Used now a days


1/16/17

1) Apache Tomcat is web server


2) GlashFish is Web + App Server
Note: On server there is special type of JVM called
Web container

26

Container
It

It

1/16/17

provides run-time environment for JavaEE (j2ee)


applications.
performs many operations that are given below:

Life Cycle Management


Multithreaded support
Object Pooling (But there

are few objects, for which creation of


new object still seems to be slight costly as they are not
considered as lightweight objects. e.g.: database connection
objects, parser objects, thread creation etc. Object Poolsare
used for this purpose.)
Security etc.

27

How to develop servlet ?


The servlet web application can be created by
three ways:
1) By implementing Servlet interface,
2) By inheriting (extending)GenericServlet class,
(or)
3) By inheriting (extending) HttpServlet class

28

How Servlet Life Cycle starts:

First

User types URL in Browser and Browser


then generates an HTTP request for this URL,
this request is then sent to appropriate Server
Second this HTTP request is received by Web
Server. The server maps this request to particular
Servlet. Now Servlet is dynamically retrieved and
loaded into address space of the server.
Now Servlet Life Cyle begins

29

Life Cycle of Servlet


1/16/17

A servlet life cycle can be defined as the entire process from its creation till
the destruction. The following are the paths followed by a servlet

The servlet is initialized by calling the init () method.

The servlet calls service() method to process a client's request.

The servlet is terminated by calling the destroy() method.


30

1/16/17

31

The init() method

1/16/17

The init method is designed to be called only once. It is called when


the servlet is first created, and not called again for each user request.
So, it is used for one-time initializations, just as with the init method
of applets.
The servlet is normally created when a user first invokes a URL
corresponding to the servlet.
When a user invokes a servlet, a single instance of each servlet gets
created, with each user request resulting in a new thread. The init()
method simply creates or loads some data that will be used
throughout the life of the servlet.
The init method definition looks like this:
public void init() throws ServletException {
// Initialization code...
}

32

The service() method

1/16/17

The service() method is the main method to perform the actual


task. The servlet container (i.e. web server) calls the service()
method to handle requests coming from the client( browsers) and
to write the formatted response back to the client.
Each time the server receives a request for a servlet, the server
spawns a new thread and calls service. The service() method
checks the HTTP request type (GET, POST, PUT, DELETE, etc.)
and calls doGet, doPost, doPut, doDelete, etc. methods as
appropriate.

Here is the signature of this method:


public void service(ServletRequest request,
ServletResponse response) throws ServletException,
IOException{
}

33

The destroy() method


The

1/16/17

destroy() method is called only once at the end of the


life cycle of a servlet. This method gives your servlet a
chance to close database connections, halt background
threads, write cookie lists or hit counts to disk, and perform
other such cleanup activities.

After

the destroy() method is called, the servlet object is


marked for garbage collection. The destroy method
definition looks like this:
public void destroy() {
// Finalization code...
}
34

Generic vs HTTP Servlet


1/16/17

Generic Servlet:
GenericServlet class is direct subclass of Servlet interface.
Generic Servlet is protocol independent.It handles all types of protocol
like http, smtp, ftp etc.
Generic Servlet only supports service() method.It handles only simple
request
public void service(ServletRequest req,ServletResponse res ).
HttpServlet:
HttpServlet class is the direct subclass of Generic Servlet.
HttpServlet is protocol dependent. It handles only http protocol.
HttpServlet supportspublic void service(ServletRequest
req,ServletResponse res ) andprotected void
service(HttpServletRequest req,HttpServletResponse res).
HttpServlet supports also
doGet(),doPost(),doPut(),doDelete(),doHead(),doTrace(),doOptions(
)etc.

35

Important servlet methods


When a servlet is first started up, its init(ServletConfig
config) method is called
init should perform any necessary initializations
init is called only once, and does not need to be threadsafe
Every servlet request results in a call to
service(ServletRequest request, ServletResponse response)
service calls another method depending on the type of
service requested
Usually you would override the called methods of interest,
not service itself
service handles multiple simultaneous requests, so it and
the methods it calls must be thread safe
When the servlet is shut down, destroy() is called
destroy is called only once, but must be thread safe
(because other threads may still be running)

1/16/17

36

Http Request Methods


Every

1/16/17

request has a header that tells the status of the client.


There are many request methods. Get and Post requests are
mostly used.
The http request methods are:
GET
POST
HEAD
PUT
DELETE
OPTIONS
TRACE

37

1/16/17

38

What is the difference between Get and


Post?
POST

1) In case of Get request,


only limited amount of
data can be sent because data
is sent in header.

In case of post request, large


amount of data can be sent
because data is sent in body.

2) Get request is not


secured because data is
exposed in URL bar.

Post request is secured because


data is not exposed in URL bar.

3) Get request can be


bookmarked

Post request cannot


be bookmarked

4) Get request is idempotent.


It means second request will be
ignored until response of first
request is delivered.

Post request is nonidempotent

5) Get request is more


efficient and used more than
Post

Post request is less


39
efficient and used less than
get.

1/16/17

GET

Content Type
1/16/17

It is a HTTP header that provides the description about


what are you sending to the browser.
text/html
text/plain
application/msword
application/vnd.ms-excel
application/jar
application/pdf
application/octet-stream
application/x-zip
images/jpeg
video/quicktime etc.

40

Steps To Create Servlet


are given 6 steps to create aservlet example.
These steps are required for all the servers.

There

1. By
2. By

servlet example can be created by three ways:

1/16/17

The

implementing Servlet interface,


inheriting GenericServlet class,
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.

The steps are as follows:

1. Create a directory structure


2. Create a Servlet
3. Compile the Servlet

41

Step-1 : Create a directory structures


1/16/17

structuredefines that where to put


the different types of files so that web container may
get the information and respond to the client.

Thedirectory

The

Sun Micro system defines a unique standard to be


followed by all the server vendors. Let's see the
directory structure that must be followed to create the
servlet.

42

Step-1 : Create a directory structures


1/16/17

43

Step-2 : Create a Servlet


HttpServlet class is widely used to create the servlet
because it provides methods to handle http requests such as
doGet(), doPost, doHead() etc.

1/16/17

The

In

our example we have created a servlet that extends the


HttpServlet class. In that example, we are inheriting the
HttpServlet class and providing the implementation of the
doGet() method. Notice that get request is the default request.

44

Writing First Servlet Class


importjavax.servlet.http.*;
importjavax.servlet.*;
importjava.io.*;

1/16/17

publicclassDemoServletextendsHttpServlet
{
publicvoiddoGet (HttpServletRequestreq, HttpServletResponseres)
throwsServletException, IOException
{
res.setContentType("text/html"); //settingthecontenttype
PrintWriterpw=res.getWriter(); //getthestreamtowritethedata

//writinghtmlinthestream
pw.println("<html><body>");
pw.println("Welcometoservlet");
pw.println("</body></html>");

pw.close(); //closingthestream
}
}

45

For

Step-3: Compile the servlet


Jar file

Server

servlet-api.jar

Apache Tomacat

weblogic.jar

Weblogic

javaee.jar

Glassfish

javaee.jar

JBoss

Ways

1/16/17

compiling the Servlet, jar file is required to be loaded.


Different Servers provide different jar files:

to load the jar file

Put the java file in any folder. After compiling the java file, paste the
class file of servlet inWEB-INF/classes directory.

46

Step-4: Create the deployment descriptor


(web.xml file)

The web container uses the Parser to get the information from
the web.xml file. There are many xml parsers such as SAX,
DOM and Pull.

1/16/17

Thedeployment descriptoris an xml file, from which Web


Container gets the information about the servlet to be invoked.

There are many elements in the web.xml file. Here is given


some necessary elements to run the simple servlet program.

47

<web-app>

<servlet>
<servlet-name>TestExample</servlet-name>
<servlet-class>DemoServlet</servlet-class>
1/16/17

<init-param>
<param-name>myName</param-name>
<param-value>myValue</param-value>
</init-param>
</servlet>

<servlet-mapping>
<servlet-name>TestExample</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>

</web-app>

48

Description of the elements of web.xml


file
1/16/17

<<
ws
s
ee
rb r
T
- v
v
hl
la
e
pe
rttp tec
>
n
m
al
r a
m
p
e
ps
ti> s
o>
n
o
g
m
>
a
n
y
el
e
m
e
n
ts

49

Configuring How a Client Accesses a


Web Application
1/16/17

You construct the URL that a client uses to access a Web


application using the following pattern:
http://hoststring/ContextPath/servletPath/pathInfo Where
hoststringis either a host name that is mapped to a
virtual host orhostname:portNumber.
ContextPathis the name of your Web application.
servletPathis a servlet that is mapped to theservletPath.
pathInfois the remaining portion of the URL, typically a
file name
Example: http://localhost:8080/Servlet_First/myServlet?
Hoststring: localhost:8080
ContextPath: Servlet_First
servletPath :
pathInfo: myServlet

50

Ports
A

port is a connection between a server and a


client
Ports are identified by positive integers
A port is a software notion, not a hardware

there may be very many of them

A service is associated
Typical port numbers:

notion, so

with a specific port

21FTP, File Transfer Protocol


22SSH, Secure Shell
25SMTP, Simple Mail Transfer Protocol
53DNS, Domain Name Service
80HTTP, Hypertext Transfer Protocol These are the ports
of most interest to us
8080HTTP (used for testing HTTP)
7648, 7649CU-SeeMe
27960Quake III
51

HttpServlet class
HttpServlet class extends the GenericServlet class and
implements Serializable interface.

It

1/16/17

The

provides http specific methods such as doGet, doPost, etc.

52

Session tracking
HTTP

1/16/17

is stateless: When it gets a page request, it


has no memory of any previous requests from the
same client
This

makes it difficult to hold a conversation


Typical example: Putting things one at a time into a
shopping cart, then checking out--each page request
must somehow be associated with previous requests
The server must be able to keep track of multiple
conversations with multiple users

Session

tracking is keeping track of what has


gone before in this particular conversation
Since HTTP is
You have to do

stateless, it does not do this for you


it yourself, in your servlets

53

Session tracking solutions


are small files that the servlet can store
on the client computer, and retrieve later
URL rewriting: You can append a unique ID after
the URL to identify the user
Hidden <form> fields can be used to store a
unique ID
The HttpSession Object

1/16/17

Cookies

Javas Session Tracking API can be used to do most


of the work for you
54

Cookies
1/16/17

l A cookie is a bit of information sent by a web server


to a browser that can later be read back from that browser.
The server can take that bit of information and use it as a
key to recover information about prior visits. This
information may be in a database or a shared object.
Cookies are read from the request object by calling
getCookies() on the request object.
Cookies are placed in the browser by calling addCookie()
on the response object.

55

Cookies
cookies are text files stored on the client computer by web
server and they are kept for various information tracking purpose
(called session tracking)
Java Servlet trasperantly support HTTP Cookies.
Cookies Contains following parameters:
Name
Value
Expiration Date
Path the Cookie is valid for
Domain the Cookie is Valid for
Need for a secure connection to exists to use the coookie.

1/16/17

56

Cookie firstName = new Cookie("first_name", request.getParameter("first_name"));

Creating Cookies
firstName = new Cookie("name",
jamesbond);
Cookies are sent using HTTP header.
To send this cookie to clients browser, servlet
must add it to response object using addCookie()
method before sending any content.
Response

1/16/17

Cookie

.addCookie(firstName);

57

Cookie firstName = new Cookie("first_name", request.getParameter("first_name"));

Retrieving Cookies
method of HttpServletRequest
returns an array of Cookie Object.
Cookie[] getCookies()

1/16/17

getCookies()

58

Cookie methods

getComment() Returns the comment describing the purpose of this


cookie, used at client side. Note that server doesnt receive this information
when
client
sends
cookie
in
request
header.
We
can
usesetComment()method to set cookie description at server side.
getDomain() returns the domain name for the cookie. We can
usesetDomain()method to set the domain name for cookie, if domain
name is set then the cookie will be sent only to that particular domain
requests.
getMaxAge() returns the maximum age in seconds. We can
usesetMaxAge()to set the expiration time of cookie.
getName() returns the name of the cookie, can be used at both browser
and server side. There is no setter for name, we can set name once through
constructor only.
getPath() Returns the path on the server to which the browser returns
this cookie. We will see its example where the cookie will be sent to specific
resource only. We can usesetPath()to instruct browser to send cookie to a
particular resource only.

1/16/17

59

Cookie methods

getSecure() Returns true if the browser is sending cookies only over a


secure protocol, or false if the browser can send cookies using any protocol.
We can usesetSecure()method to instruct browser to send cookie only
over secured protocol.
getValue() returns the value of the cookie as String. There is
alsosetValue()method to change the value of cookie.
getVersion() Returns the version of the protocol this cookie complies
with. There is also a setter method for version.
isHttpOnly() Checks whether this Cookie has been marked as HttpOnly.
There is also a setter method that we can use to instruct client to use it for
HTTP only.

1/16/17

60

URL-Rewriting
Idea

appends some extra data on the end of each URL that


identifies the session
Server associates that identifier with data it has stored
about that session
E.g., http://host/path/file.html;jsessionid=1234

Advantage
Works

even if cookies are disabled or unsupported

Disadvantages

Must encode all URLs that refer to your own site


All pages must be dynamically generated
Fails for bookmarks and links from other sites

61

1/16/17

Client

Hidden Form Fields


HTML pages with forms that store
hidden information

<INPUT TYPE="HIDDEN" NAME="session" VALUE="...">

Advantage
Works

even if cookies are disabled or unsupported

Disadvantages
Lots of tedious processing as Extra form
submission is required on each pages.
Only textual information can be used.
All

pages must be the result of form submissions

62

1/16/17

Generate

HTTP Session
1/16/17

63

The HttpSession Object:


1/16/17

64

Cookies vs session
Cookie

Session is stored in server

Cookie is stored in Client

Session works regardless of the


settings on the client browser.

Cookies works according to


clients web-browser setting.

Unlimited data can be stored.

Limited data can be stored.

It can store Objects.

It can only store Strings.

Slower than Cookie.

Faster than Seeion.

1/16/17

Session

65

ServletConfig
1/16/17

object of ServletConfig is created by the web


container for each servlet. This object can be used
to get configuration information from web.xml
file.
Advantage of ServletConfig :
The core advantage of ServletConfig is that you
don't need to edit the servlet file if information is
modified from the web.xml file.
An

66

Methods of ServletConfig interface


String getInitParameter(String
name):Returns the parameter value for the
specified parameter name.
public Enumeration
getInitParameterNames():Returns an
enumeration of all the initialization parameter
names.
public String getServletName():Returns the
name of the servlet.
public ServletContext
getServletContext():Returns an object of
ServletContext.

1/16/17

public

67

ServletContext
This

set the attributes for application level


and get the initialization parameter values

web.xml

It

1/16/17

is an interface.
It is used to communicate with ServletContainer.
Due to this there is only one servletContext for
the whole project/application.
It is used to
from

is used to

the MIME(Multipurpose Internet Mail


Extensions) type of a file
get dispatch requests
and write to a log file
get

68

ServletContext methods
String

1/16/17

getInitParameter(Stringname)
Enumeration getInitParameterNames()
Object getAttribute(Stringname)
Enumeration getAttributeNames()
void setAttribute(Stringname, Objectobject)
void removeAttribute(Stringname)
String getRealPath(Stringpath)<input
type="hidden" name="sessionID"
value="..."><input type="hidden"
name="sessionID" value="...">
RequestDispatcher getRequestDispatcher(String
path)

69

ServletConfig

6.We should give request explicitly,


in order to create ServletConfig
object for the first time

1.ServletContext available in
javax.servlet.*; package
2.ServletContext object is global to
entire web application
3.Object of ServletContext will be
created at the time of web
application deployment
4.Scope: As long as web application
is executing, ServletContext object
will be available, and
5. it will be destroyed once the
application is removed from the
server.
6.ServletContext object will be
available even before giving the first
request

1/16/17

1.ServletConfig available in
javax.servlet.*; package
2.ServletConfig object is one per
servlet class
3. Object of ServletConfig will be
created during initialization process
of the servlet
4. destroyed once the servlet
execution is completed.
5.This Config object is public to a
particular servlet only

ServletContext

70

Servlet Filter
an object that is invoked at the
preprocessing and postprocessing of a request.
It is mainly used to perform filtering tasks such
as conversion, logging, compression, encryption
and decryption, input validation etc.
Theservlet filter is pluggable, i.e. its entry is
defined in the web.xml file, if we remove the entry
of filter from the web.xml file, filter will be
removed automatically and we don't need to
change the servlet.

1/16/17

Afilteris

71

Servlet Filters
1/16/17

Uses of Filters
l Authentication - Blocking requests based on user identity.
Logging and auditing - Tracking users of a web application.
Image conversion - Scaling maps, and so on.
Data compression - Making downloads smaller.
Localization - Targeting the request and response to a
particular locale.
Encryption
Debugging

72

Filter API

1/16/17

Like servlet filter have its own API. The


javax.servlet package contains the three interfaces
of Filter API.
Filter
FilterChain
FilterConfig

73

Filter Interface
Desription

public void init(FilterConfig


config)

init() method is invoked only


once. It is used to initialize the
filter.

public void
doFilter(HttpServletRequest
request,HttpServletResponse
response, FilterChain chain)

doFilter() method is invoked


every time when user request to
any resource, to which the filter
is mapped.It is used to perform
filtering tasks.

public void destroy()

This is invoked only once when


filter is taken out of the service.

1/16/17

Method

74

Filter Chain interface


The

1/16/17

object of FilterChain is responsible to invoke


the next filter or resource in the chain.This object
is passed in the doFilter method of Filter
interface.The FilterChain interface contains only
one method:
public
void doFilter(HttpServletRequest
request, HttpServletResponse response):it
passes the control to the next filter or resource.
Called

by Container each time a request/response pair


is passed through the chain due to a client request for a
resource at the end of the chain.

75

Filter Config
is used by a servlet container to pass
information to a filter during initailization.
4 methods:
1) String getFilterName()
2) String getInitParameter()
3) Enumeration getInitParameterNames()
4) ServletContext getServletContext()

1/16/17

It

76

How to define filter in web.xml


1/16/17

<web-app>

<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name> servlet1 </servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>

<filter>
<filter-name>MyFilter</filter-name>
<filter-class>MyFilter</filter-class>
</filter>

<filter-mapping>
<filter-name> MyFilter </filter-name>
<url-pattern>/servlet1</url-pattern>
</filter-mapping>
</web-app>

77

How to write filter code


1/16/17

importjava.io.IOException;
importjava.io.PrintWriter;
importjavax.servlet.*;
publicclassMyFilterimplementsFilter{
publicvoidinit(FilterConfigarg0)throwsServletException{}

publicvoiddoFilter(ServletRequestreq,ServletResponseresp,
FilterChainchain)throwsIOException,ServletException{

PrintWriterout=resp.getWriter();
out.print("filterisinvokedbefore");

chain.doFilter(req,resp);//sendsrequesttonextresource

out.print("filterisinvokedafter");
}
publicvoiddestroy(){}
}

78

Servlet code
1/16/17

importjava.io.IOException;
importjava.io.PrintWriter;

importjavax.servlet.ServletException;
importjavax.servlet.http.*;

publicclassHelloServletextendsHttpServlet{
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{

response.setContentType("text/html");
PrintWriterout=response.getWriter();

out.print("<br>welcometoservlet<br>");

79

Servlet Events
An event refers to a set of actions that may occur while an
application is running.
It could also be defined as a set of actions, such as clicking a button
or pressing a key, performed by a user.
The following list shows some of the events that may occur during
the life cycle of a servlet:
Initializing servlets.
Adding, removing or replacing attributes in ServletContext.
Creating, activating Session.
Adding, removing, or replacing attributes in a servlet session.
Destroying servlets

1/16/17

80

Event and Listener in Servlet


Events

are basically occurrence of something.


Changing the state of an object is known as an
event.
We can perform some important tasks at the
occurrence of these exceptions, such as counting
total and current logged-in users, creating tables
of the database at time of deploying the project,
creating database connection object etc.
There are many Event classes and Listener
interfaces
in
the
javax.servlet
and
javax.servlet.http packages.

Types of Servlet Events


Request level events: Refers to the events related to the clients
1/16/17

information to a servlet.
There are two event listeners
1. ServletRequestListner
2. ServletRequestAttributeListner

Servlet Context level events: Refer to the application level events


There are two event listeners
1. ServletContextListner
2. ServletContextAttributeListne

Servlet Session level events: Refers to the events that are used to
maintain the session of a client.
There are three event listeners
1. HttpSessionListner
2. HttpSessionAttributeListner
3. HttpSessionActivationListner
82

Event classes
ServletRequestEvent

ServletRequestAttributeEvent
ServletContextEvent

ServletContextAttributeEvent
HttpSessionEvent

HttpSessionBindingEvent

Event interfaces
ServletRequestListener

ServletRequestAttributeListener
ServletContextListener

ServletContextAttributeListener
HttpSessionListener

HttpSessionAttributeListener
HttpSessionBindingListener

HttpSessionActivationListener

Servletrequest event and ServletRequestlistener

1) Void

requestIniatialized(ServletRequestEvent e)
It is invoked when request is about to come into
scope of the web application.
2) Void requestDestroyed(ServletRequestEvent e)
It is invoked when request is about to go out of
scope of the web application.

1/16/17

Methods

85

ServletContextEvent and
ServletContextListener
If

you want to perform some action at the time of


deploying the web application such as creating
database connection, creating all the tables of the
project
etc,
you
need
to
implement
ServletContextListener interface and provide the
implementation of its methods.
ServletContextListener will be executed once your
web application is deployed in your application
server (Tomcat or etc). If you have any
requirements that need to be executed before the
application is started, ServletContextListener is
the best place for you.

Method

of ServletContextEvent class
There is only one method defined in the
ServletContextEvent class:
public ServletContext getServletContext():
returns the instance of ServletContext.
Methods of ServletContextListener interface
There are two methods declared in the
ServletContextListener interface which must be
implemented by the servlet programmer to
perform some action such as creating database
connection etc.
public void
contextInitialized(ServletContextEvent e): is

1/16/17

88

HttpSessionEvent and
HttpSessionListener
The

HttpSessionEvent is notified when session


object is changed. The corresponding Listener
interface for this event is HttpSessionListener.
We can perform some operations at this event
such as counting total and current logged-in
users, maintaing a log of user details such as
login time, logout time etc.

Methods of HttpSessionListener
interface
There are two methods declared in the
HttpSessionListener interface which must be
implemented by the servlet programmer to perform
some action
.public
void
sessionCreated(HttpSessionEvent
e):
is
invoked when session object is created.
public
void
sessionDestroyed(ServletContextEvent e): is
invoked when session is invalidated.

1/16/17

Tomcat is both a web server and a web container, but it's not really
meant to function as a high performance web server, nor does it
include some features typical of a web server. Tomcat is meant to
be used in conjunction with the Apache web server, where Apache
manages static pages, caching, redirection, etc. and Tomcat
handles the container (web application) functions. You'll often hear
the phrase "Apache Tomcat" together, which is both a proper
attribution of the Tomcat project (as part of the Apache Foundation),
but also appropriate as a label, as they're usually used together as
a package.

91

Read

Servlets Tasks

1/16/17

the explicit data sent by the clients (browsers). This


includes an HTML form on a Web page or it could also come
from an applet or a custom HTTP client program.
Read the implicit HTTP request data sent by the clients
(browsers). This includes cookies, media types and
compression schemes the browser understands, and so forth.
Process the data and generate the results. This process may
require talking to a database, executing an RMI call, invoking
a Web service, or computing the response directly.
Send the explicit data (i.e., the document) to the clients
(browsers). This document can be sent in a variety of formats,
including text (HTML or XML), binary (GIF images), Excel,
etc.
Send the implicit HTTP response to the clients (browsers).
This includes telling the browsers or other clients what type of
document is being returned (e.g., HTML), setting cookies and
92
caching parameters, and other such tasks.

Difference between Applet and


Servlet
1/16/17

93

Apache
Apache

1/16/17

Apache is a very popular server


66% of the web sites on the Internet use
Apache is:
Full-featured and extensible
Efficient
Robust
Secure (at least, more secure than other
Up to date with current standards
Open source
Free

servers)

94

Tomcat
Tomcat

Tomcat is a helper application for Apache


Its best to think of Tomcat as a servlet container

Apache

Apache
Tomcat

Its

1/16/17

is the Servlet Engine than handles servlet


requests for Apache
can handle many types of web services
can be installed without Tomcat
can be installed without Apache

easier to install Tomcat standalone than as part


of Apache
By

itself, Tomcat can handle web pages, servlets, and JSP

Apache

free)

and Tomcat are open source (and therefore

95

S-ar putea să vă placă și