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

Servlet Introduction

A servlet is a Java program that runs on a web server and responds to requests from clients. It has a lifecycle with initialization, service, and destruction methods. The HttpServlet class provides HTTP-specific functionality by overriding methods like doGet and doPost. To deploy a servlet, it must be compiled and packaged with other files into a WAR file or copied to the webapps folder along with the web.xml deployment descriptor defining servlet mappings. On startup, the servlet container loads and initializes the servlet class to handle requests.

Uploaded by

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

Servlet Introduction

A servlet is a Java program that runs on a web server and responds to requests from clients. It has a lifecycle with initialization, service, and destruction methods. The HttpServlet class provides HTTP-specific functionality by overriding methods like doGet and doPost. To deploy a servlet, it must be compiled and packaged with other files into a WAR file or copied to the webapps folder along with the web.xml deployment descriptor defining servlet mappings. On startup, the servlet container loads and initializes the servlet class to handle requests.

Uploaded by

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

Servlet: Introduction

New methods added in HTTPServlet 10


HTTPServlet 9
GenericServlet 8
Servlet Class hierarchy 7
Servlet instance 6
Servlet Lie Cycle !
Servlet interace "
#S$% &
Servlet 'e()est 'es*onse +echanism ,
$einition 1
Contents

$e*loyin- ,0
Pac.a-in- 19
/ritin- we012ml 18
we012ml 17
3rie introd)ction to 4+L 16
$e*loyment $escri*tors 1!
HT+L ile with a lin. to servlet 1"
Ste*s to de*loy a we0 a**lication 1&
5 Sim*le Servlet 1,
'e()est and 'es*onse o06ect 11
Contents

Gettin- sin-le *arameters &0
Htt*Servlet'es*onse 7nterace ,9
Servlet'es*onse 7nterace ,8
Htt*Servlet'e()est 7nterace ,7
Servlet'e()est ,6
'e()est and 'es*onse hierarchy ,!
82ec)tion ,"
$e*loyment ,&
Ste*s or *ac.a-in- ,,
Pac.a-in- and de*loyin- the servlet ,1
Contents

Sin-leThread+odel 7nterace &"
Servlet varia0le initiali9ation &&
Servlet to -et m)lti*le *aram &,
Gettin- m)lti*le *arameters &1
Contents

Know

What a servlet is and its lifecycle

The Request Response Mechanism

Servlet classes

HttpServletRequest and HttpServletResponse


classes

Be Able To

Write a simple servlet



Definition

A servlet is a server side proram !ritten


in "ava that resides and e#ecutes in an
application server

$t enables the delivery of dynamic content



Servlet Request Response Mechanism
Servlet
Database
Client
Web Server
Application Server
Request
Response
If request is for static page
return the page as response
Else
Pass the request to application server

"SD%

"ava Servlet Development %it &"SD%'


contains the class library that is required
to create servlets and "S()

The * pac+aes that are required to create


servlets are javax.servlet and
javax.servlet.http.

A ,ava class is a servlet if it directly or


indirectly implements the Servlet
interface)

Servlet interface

public void init(ServletConfig


config) throws ServletException

public void service(ServletRequest


req, ServletResponse res) throws
ServletException,
java.io.!Exception

public void destro"()

public ServletConfig
getServletConfig()

public String getServletnfo()


Life cycle methods

Servlet instance
Servlet
Instantiation
New instance
created on first
request
Initialized Servlet
init() is called
Application Server
Request servicing
Servlet
service() is called
Destroyed
Servlet
destroy() is called
Initialization
Begin service
Destruction
Servlet -ife .ycle
First request
Subsequent requests

Servlet instance

/nly one instance of a particular servlet


class is created) The same instance is
used for all the requests)

When the container shuts do!n0 this


instance is destroyed)

Servlet instance

The container runs multiple threads on the


service&' method to process multiple
requests)

/nly a sinle instance of servlet of each


type ensures minimum number of servlet
ob,ects created and destroyed on the
server
1
adds to scalability

Servlet .lass hierarchy
javax.servlet.GenericServlet
javax.servlet.http.HttpServlet
javax.servlet.Servlet

2enericServlet

2enericServlet class provides basic


implementation of the Servlet interface)

This is an abstract class) $t implements all the


methods e#cept service&' method)

2enericServlet

/ther methods included are3

public void log(String #essage)

public void init() throws


ServletException

The implementation of
init(ServletConfig config)calls
init()method)

HTT(Servlet

HTT(Servlet inherits from the


2enericServlet and provides a HTT(
specific implementation of the Servlet
interface)

The service&ServletRequest req0


ServletResponse res' method is
implemented)

HTT(Servlet

Since this implementation specific to


HTT( protocol0 there are methods that
specific to each HTT( methods li+e 24T0
(/ST0 TRA.4 etc)

$t is an abstract class and is subclassed to


create an HTT( servlet suitable for a Web
site)

5e! methods added in HTT(Servlet
protected void
service($ttpServletRequest req,
$ttpServletResponse res) throws
ServletException, java.io.!Exception
protected void do%%%($ttpServletRequest
req, $ttpServletResponse res)
%%% is &E', (!S', 'R)CE, (*', +E,E'E

A subclass of HttpServlet must override

at least one method0 usually one of do&et,


do(ost, do+elete, do(ut, do$ead

init and destro" to manae resources that


are held for the life of the servlet)
Our focus

Request and Response ob,ect
Servlet A
Request for
servlet A
Response
Client
Web Server
Application server
HTTP
request
packet
$ttpServletRequest !bject
$ttpServletResponse !bject
Web Container
HTTP
response
packet

A Simple Servlet
i#port javax.servlet.http.-.
i#port javax.servlet.-.
i#port java.io.-.
public class &reetingServlet extends
$ttpServlet /
String welco#e0sg
123elco#e to si#ple servlet4.
java.util.+ate curr+ate.
reet)!ar

public void do&et($ttpServletRequest
request,$ttpServletResponse response)
throws ServletException, !Exception /
curr+ate1new java.util.+ate().
(rint3riter out 1 response.get3riter().
response.setContent'"pe(5text6ht#l5).

out.println(57ht#l87head87title8&reeting
s Servlet 76title876head84).
out.println(57bod"849
welco#e0sg947br849curr+ate9
476bod"876ht#l85).
::

Steps to deploy a !eb application

Write servlets) .ompile them)

Write html and ,sp files)

Write deployment descriptor !eb)#ml)

(ac+ae the application

Deploy the application



HTM- file !ith a lin+ to servlet
7ht#l87head8
7title8&reet76title8
76head8
7bod"8
7h;8Si#ple Exa#ple76h;8
Clic< to invo<e the servlet
7a href12greet.do48&reetings76a8
76bod"8
76ht#l8
index.html
We !ill map the servlet and the url shortly

Deployment Descriptor

Deployment descriptors is an #ml file that helps in


manain the confiuration of an application)

This is the file usin !hich an application can


communicate !ith the container and vice versa)

6or a !eb application0 the deployment descriptor file


name is !eb)#ml)

The "ava Servlet specifies a document type


definition for deployment descriptor !hich is
available at
http=66java.sun.co#6j>ee6dtds6web?app?>?>.dtd

Brief introduction to 7M-

7M- stands for 47tensible Mar+up -anuae)


7M- is a mar+up lanuae much li+e HTM-)

7M- !as desined to describe data) 7M- !as


created to structure0 store and to send
information)

7M- is a cross8platform0 soft!are and hard!are


independent tool for transmittin information)

7M- tas are not predefined) 9ou must define


your o!n tas)

/ne of the uses of 7M- is to e#chane data)



!eb)#ml

Servlet components that are used in !eb


application alon !ith their fully qualified class
names

:R-s for servlets

Welcome file name

$nitiali;ation parameters if any

Session .onfiuration

Application -ifecycle -istener classes

6ilter Definitions and 6ilter Mappins

4rror (aes

4nvironment <ariable Mappins

Mime type mappin


/ur focus in this chapter

Writin !eb)#ml
7web@app8
7displa"@na#e8&reet76displa"@na#e8
7servlet8
7servlet@na#e8&reet76servlet@na#e8
7displa"@na#e8si#ple76displa"@na#e8
7servlet@class8
&reetingServlet76servlet@class8
76servlet8

Optional I!E"s use it for listing #eb
application name
Identifier for this servlet in the #eb appliaction
$ully qualified name for the servlet

7servlet@#apping8
7servlet@na#e8&reet76servlet@na#e8
7url@pattern8
6greet.do76url@pattern8
76servlet@#apping8

76web@app8
%ppend a & for tomcat
'(L that is going to used to access this
component
specify the identifier for #hich
component url is going to be mapped
7welco#e@file@list8
7welco#[email protected]#l76welco#e@file8
7welco#[email protected]#e@file8
76welco#e@file@list8
Optional because inde)html is #elcome file by default*
If inde)html is not found+ container #ill loo, for default-sp)

(ac+ain

(ac+ain application means placin the


files in the appropriate placeholders
&directory')

(ac+ain

Servlet specification lays out the rules of ho!


enterprise applications should be pac+aed)

This is necessary so that the container &any ,*ee


container' +no!s !here to find the files &the
servlet class files0 html class files etc)'

Since a !eb application is composed of many


files0 the specification also tells us ho! to
archive the files and deploy it as sinle file
application)

Deployin

Deployin means uploadin the


application on the server)

$f there is any problem !ith the pac+ain0


the application !ill not be uploaded)

There are many "*44 $D4s that help in


developin and pac+ain the application)

Deployin

Most of the application servers support hot


deployment)

Most of the application servers support


start and stop of applications that are
deployed)

(ac+ain and deployin the servlet
We Application !
Servlets
"S#s$%&'(
"ava
)lasses
Deploy*ent
Descriptor
(web.xml)
We Application +
Servlets
"S#s$%&'(
"ava
)lasses
Deploy*ent
Descriptor
(web.xml)
Components forming the web application.
xxx#ar

Steps for pac+ain

.reate a folder)

-et us name the folder as slide=e#=)

(lace htmls and ,sps in folder

(lace the inde#)html inside slide=e#=

.reate a folder called W4B8$56)

.reated> 5ote the case is important here)

(lace !eb)#ml inside the folder

(laced>

.reate a folder called classes inside W4B8$56


and all the ,ava classes created inside it)

.reated and placed 2reetinServlet)class)



Deployment

As per ,*ee specification0 a ,ar file should be


created !ith the e#tension )!ar) This !ar file
has to be then deployed dependin on the
application server)

"ar .ommand to create !ar

path6si#ple=8 jar Acvf si#ple.war


-.-

6or tomcat0 ,ust copy the simple folder into the


folder called !ebapps)


Deployment

Start the tomcat server)

Type in the follo!in url in the address bar

http=66localhost=BCBC6slide;ex;
6index.ht#l

!r si#pl"

http=66localhost=BCBC6slide;ex;
Server name
!efault protocol #here tomcat runs
protocol
$older name

According to j2ee
specs, war file has to
be created. For
tomcat we dont do
so. So, does this
mean that tomcat
does not strictly
follow j2ee specs.
Tomcat follows
j2ee specs! It jst
gi!es yo a simple
way to deploy yor
application.
Another option to
deploy wold be to
place the war file
in the webapps
folder!

Request and Response hierarchy
%ttpServletResponse
ServletResponse
%ttpServletRequest
ServletRequest

ServletRequest

DufferedReader getReader()

ServletnputStrea#
getnputStrea#()

int getContent,ength()

Enu#eration get(ara#eterEa#es()

String get(ara#eter(String na#e)

StringFG get(ara#eterHalues(String
na#e)
E)ample ahead
%llo#s you to read ra# bytes
or characters from the stream

HttpServletRequest $nterface

String get0ethod()

String get$eader(String na#e)

Enu#eration get$eaderEa#es()

String getIuer"String()

Coo<iesFG getCoo<ies()

$ttpSession getSession()
/00P
protocol
specific
method
s
Later

ServletResponse $nterface

void setContent'"pe(String t"pe)

void setContent,ength(int len)

Servlet!utputStrea#
get!utputStrea#()

(rint3riter get3riter()
%llo#s us to #rite
into the response
stream
"e ha!e seen
this !

HttpServletResponse $nterface

void addCoo<ies(Coo<ie c)

String add$eader(String na#e,String


value)

void sendRedirect(String url)

void sendError(int ecode)



2ettin sinle parameters
In the do1et23 method #e can get the value entered
by the user in the html form using:
String boo<title1
request.get(ara#eter(2na#e4).
J
7h;8,ocate Doo<s76h;8
7for# action12boo<.do48
7input t"pe12text4
na#e12na#e48
7input t"pe12sub#it48
76for#8
J
!efault is 1E0
boo+)!ar

?uestion@

What !ill happen if your form has a post


method0 and the servlet that the form calls has
only do2et&' method@

2ettin multiple parameters
J
7for# #ethod15(!S'5 action15displa".do58
7p8Select Colors=7br8
7input t"pe15chec<box5 na#e15color5
value15Red58Red7br8
7input t"pe15chec<box5 na#e15color5
value15&reen58 &reen7br8
7input t"pe15chec<box5 na#e15color5
value15Dlue58Dlue76p8
7p87input t"pe15sub#it5 value15Sub#it5
na#e15D;587input t"pe15reset5
value15Reset5 na#e15D>5876p8
76for#8
J

Servlet to et multiple param
public class Colors extends
javax.servlet.http.$ttpServlet/
public void do(ost(
javax.servlet.http.$ttpServletRequest
req,
javax.servlet.http.$ttpServletResponse
res)
throws java.io.!Exception,
javax.servlet.ServletException/
java.io.(rint3riter out1res.get3riter().
out.println(57ht#l85).

String
colorsFG1req.get(ara#eterHalues(5color5).
out.println(57bod"85).
for(int i1C.i7colors.length.i99)
out.println(57font color1K59
colorsFiG95K8$ello 76font87br85 ).
out.println(576bod"876ht#l85).
:
:
reet)!ar

?uestion@
What happens if
you don"t select
any of the
chec,bo)es.

Servlet variable initiali;ation

$nitiali;ation of servlet variables is enerally


done in init&' method)

$n the normal class0 initiali;ation happens in the


constructor) But since the container calls the
constructor in this case0 havin parameteri;ed
constructor has no meanin)

The initiali;ation values are passed to servlet


throuh DD and are available only from init&'
method on!ards)

Therefore0 the initiali;ation is done in init&'


method)
2enerally one never !rites a constructor for a servlet>>

SinleThreadModel $nterface

$n the servlet model that !e have seen so far0 a


sinle servlet processes multiple requests
simultaneously)

This means that the do2et and do(ost methods


must be careful to synchroni;e access to fields and
other shared data0 since multiple threads may be
tryin to access the data simultaneously)

/n the other hand0 you can have your servlet


implement the Single'hread0odel interface0 as
belo!)

public class LourServlet extends


$ttpServlet i#ple#ents
Single'hread0odel /...:
And say goodbye
to Scalability

You might also like