Sie sind auf Seite 1von 26

Servlets

Aravinda.C.V

22 Sep 2011

Servers

A server is a computer that responds to requests from a client

Typical requests: provide a web page upload or download a file send email

A server is also the software that responds to these requests! a client could be the browser or other software ma"ing these requests Typically your little computer is the client and someone else#s big computer is the server

$owever any computer can be a server %t is not unusual to have server software and client software running on the same computer

Apache

Apache is a very popular server

''( of the web sites on the %nternet use Apache )ull*featured and e+tensible ,fficient -obust Secure .at least more secure than other servers/ 0p to date with current standards 1pen source )ree

Apache is:

2hy use anything else3


&

5orts

A port is a connection between a server and a client


5orts are identified by positive integers A port is a software notion not a hardware notion so there may be very many of them Typical port numbers:

A service is associated with a specific port

216)T5 )ile Transfer 5rotocol 226SS$ Secure Shell 256S7T5 Simple 7ail Transfer 5rotocol 53689S 8omain 9ame Service 80HTTP, Hypertext Transfer Protocol 8080HTTP (used for testing HTTP) 7648 76496C0*See7e 279606:ua"e %%%

These are the ports of most interest to us

5orts %%

7y 05enn 2eb page is:


http://www.cis.upenn.edu/~matuszek

<ut it is also:
http://www.cis.upenn.edu:80/~matuszek

The http: at the beginning signifies a particular protocol .communication language/ the $yperte+t Transfer 5rotocol The :80 specifies a port <y default the 2eb server listens to port 80

The 2eb server could listen to any port it chose This could lead to problems if the port was in use by some other server )or testing servlets we typically have the server listen to port 8080 %f % had sent it to some other port say 99 my request would either go unheard or would .probably/ not be understood

%n the second 0-= above % e+plicitly sent my request to port 80

C>% Scripts

C>% stands for ?Common >ateway %nterface@


Client sends a request to server Server starts a C>% script Script computes a result for server and quits Server returns response to client Another client sends a request Server starts the C>% script again ,tc. client client

server
script

'

Servlets

A servlet is li"e 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 Another client sends a request Server calls the servlet again ,tc. client client

server
servlet

Servlets vs. C>% scripts

Advantages:

-unning a servlet doesn#t require creating a separate process each time A servlet stays in memory so it doesn#t have to be reloaded each time There is only one instance handling multiple requests not a separate instance for every request 0ntrusted servlets can be run in a ?sandbo+@ =ess choice of languages .C>% scripts can be in any language/

8isadvantage:

Tomcat

Tomcat is the Servlet ,ngine than handles servlet requests for Apache

Tomcat is a ?helper application@ for Apache %t#s best to thin" of Tomcat as a ?servlet container@ Apache can be installed without Tomcat Tomcat can be installed without Apache

Apache can handle many types of web services


%t#s easier to install Tomcat standalone than as part of Apache

<y itself Tomcat can handle web pages servlets and DS5

Apache and Tomcat are open source .and therefore free/ C

Servlets

A servlet is any class that implements the ja a!.se" #et.$e" #et interface

%n practice most servlets e+tend the ja a!.se" #et.http.%ttp$e" #et class Some servlets e+tend ja a!.se" #et.&ene"ic$e" #et instead

Servlets li"e applets usually lac" a main method but must implement or override certain other methods

EF

%mportant servlet methods %

2hen a servlet is first started up its init'$e" #et()n*i+ config, method is called

init should perform any necessary initialiGations init is called only once and does not need to be thread*safe

,very servlet request results in a call to se" ice'$e" #et-e.uest request/ $e" #et-esp)nse response,

se" ice calls another method depending on the type of service requested 0sually you would override the called methods of interest not se" ice itself se" ice handles multiple simultaneous requests so it and the methods it calls must be thread safe dest")0 is called only once but must be thread safe .because other threads may still be running/

2hen the servlet is shut down dest")0', is called

EE

$TT5 requests

2hen a request is submitted from a 2eb page it is almost always a &12 or a 34$2 request The $TT5 5*)"m6 tag has an attribute acti)n whose value can be 7+et7 or 7p)st7 The 7+et7 action results in the form information being put after a 8 in the 0-=

,+ample: http://www.+))+#e.c)m/sea"ch8h#9en:ie9;2<=8:)e9;2<= 8:.9se" #ets The : separates the various parameters 1nly a limited amount of information can be sent this way

7put7 can send large amounts of information E2

%mportant servlet methods %%

The se" ice method dispatches the following "inds of requests: >1?121 &12 %1@> 432A4B$ 34$2 3;2 and 2-@(1

A &12 request is dispatched to the d)&et'%ttp$e" #et-e.uest "e.uest/ %ttp$e" #et-esp)nse "esp)nse, method A 34$2 request is dispatched to the d)3)st'%ttp$e" #et-e.uest "e.uest/ %ttp$e" #et-esp)nse "esp)nse, method These are the two methods you will usually override d)&et and d)3)st typically do the same thing so usually you do the real wor" in one and have the other Hust call it puC#ic )id d)&et'%ttp$e" #et-e.uest "e.uest/ %ttp$e" #et-esp)nse "esp)nse, D d)3)st'"e.uest/ "esp)nse,E F

E&

A ?$ello 2orld@ servlet


.from the Tomcat installation documentation/

puC#ic c#ass %e##)$e" #et e!tends %ttp$e" #et D puC#ic )id d)&et'%ttp$e" #et-e.uest "e.uest/ %ttp$e" #et-esp)nse "esp)nse, th")ws $e" #et1!cepti)n/ A41!cepti)n D "esp)nse.set()ntent20pe'7te!t/htm#7,E 3"intG"ite" )ut 9 "esp)nse.+etG"ite"',E $t"in+ d)c20pe 9 75H>4(2I31 %2J? 3;K?A( L7=//G3(//>2> %2J? 4.0 7 M 72"ansiti)na#//1BL76Ln7E )ut.p"int#n'd)c20pe M 75%2J?6Ln7 M 75%1@>652A2?16%e##)5/2A2?165/%1@>6Ln7 M 75K4>I K&(4?4-9L7N<><516L76Ln7 M 75%16%e##) G)"#d5/%16Ln7 M 75/K4>I65/%2J?67,E F F 8on#t worry we#ll ta"e this a little at a timeI

E4

The superclass

puC#ic c#ass %e##)$e" #et e!tends %ttp$e" #et D ,very class must e+tend &ene"ic$e" #et or a subclass of &ene"ic$e" #et

&ene"ic$e" #et is ?protocol independent @ so you could write a servlet to process any protocol %n practice you almost always want to respond to an $TT5 request so you e+tend %ttp$e" #et

A subclass of %ttp$e" #et must override at least one method usually one d)&et d)3)st d)3ut d)>e#ete init and dest")0 or +et$e" #etAn*)
E;

The d)&et method

puC#ic )id d)&et'%ttp$e" #et-e.uest request/ %ttp$e" #et-esp)nse response, th")ws $e" #et1!cepti)n/ A41!cepti)n D This method services a &12 request The method uses "e.uest to get the information that was sent to it The method does not return a value! instead it uses "esp)nse to get an %J1 stream and outputs its response Since the method does %J1 it can throw an A41!cepti)n Any other type of e+ception should be encapsulated as a $e" #et1!cepti)n The d)3)st method wor"s exactly the same way E'

5arameters to d)&et

%nput is from the %ttp$e" #et-e.uest parameter

1ur first e+ample doesn#t get any input so we#ll discuss this a bit later

1utput is via the %ttp$e" #et-esp)nse obHect which we have named "esp)nse

%J1 in Dava is very fle+ible but also quite comple+ so this obHect acts as an ?assistant@

EA

0sing the %ttp$e" #et-esp)nse

The second parameter to d)&et .or d)3)st/ is %ttp$e" #et-esp)nse "esp)nse ,verything sent via the 2eb has a ?7%7, type@ The first thing we must do with "esp)nse is set the MIME type of our reply: "esp)nse.set()ntent20pe'7te!t/htm#7,E

This tells the client to interpret the page as $T7=

<ecause we will be outputting character data we need a 3"intG"ite" handily provided for us by the +etG"ite" method of "esp)nse: 3"intG"ite" )ut 9 "esp)nse.+etG"ite"',E 9ow we#re ready to create the actual page to be returned EB

0sing the 3"intG"ite"

)rom here on it#s Hust a matter of using our 3"intG"ite" named )ut to produce the 2eb page )irst we create a header string:
$t"in+ d)c20pe 9 75H>4(2I31 %2J? 3;K?A( L7=//G3(//>2> %2J? 4.0 7 M 72"ansiti)na#//1BL76Ln7E This line is technically required by the $T7= spec <rowsers mostly don#t care but $T7= validators do care

Then use the p"int#n method of )ut one or more times


)ut.p"int#n'd)c20pe M 75%2J?6Ln7 M 75%1@>6 ... 5/K4>I65/%2J?67,E

And we#re doneI EC

%nput to a servlet

A &12 request supplies parameters in the form

URL 8 name=value : name=value : name=value .%llegal spaces added to ma"e it more legible/ Actual spaces in the parameter values are encoded by + signs 1ther special characters are encoded in he+! for e+ample an ampersand is represented by O26

5arameter names can occur more than once with different values A 34$2 request supplies parameters in the same synta+ only it is in the ?body@ section of the request and is therefore harder for the user to see
2F

>etting the parameters

%nput parameters are retrieved via messages to the %ttp$e" #et-e.uest obHect request

7ost of the interesting methods are inherited from the superinterface $e" #et-e.uest -eturns an 1nume"ati)n of the parameter names %f no parameters returns an empty 1nume"ati)n -eturns the value of the parameter name as a String %f the parameter doesn#t e+ist returns nu## %f name has multiple values only the first is returned -eturns an array of values of the parameter name %f the parameter doesn#t e+ist returns nu##

puC#ic 1nume"ati)n +et3a"amete"Bames',


puC#ic $t"in+ +et3a"amete"'$t"in+ name,


puC#ic $t"in+PQ +et3a"amete"Ra#ues'name,


2E

1nume"ati)n review

An 1nume"ati)n is almost the same as Ate"at)"

%t#s an older class and the names are longer 1nume"ati)n e 9 m0Rect)".e#ements',E whi#e 'e.hasJ)"e1#ements',, D $0stem.)ut.p"int#n'e.ne!t1#ement',,E F

,+ample use:

22

,+ample of input parameters


puC#ic )id d)&et'%ttp$e" #et-e.uest "e.uest/ %ttp$e" #et-esp)nse "esp)nse, D ... stuff omitted ... )ut.p"int#n'75%16%e##)7,E $t"in+ namesPQ 9 "e.uest.+et3a"amete"Ra#ues'7name7,E i* 'names H9 nu##, *)" 'int i 9 0E i 5 names.#en+thE iMM, )ut.p"int#n'7 7 M namesPiQ,E )ut.p"int#n'7H7,E F
2&

Dava review: 8ata from Strings


All parameter values are retrieved as $t"in+s )requently these Strings represent numbers and you want the numeric value

int n 9 new Ante+e"'param,.intRa#ue',E d)uC#e d 9 new >)uC#e'param,.d)uC#eRa#ue',E C0te C 9 new K0te'param,.C0teRa#ue',E


Similarly for sh)"t *#)at and #)n+ These can all throw a BumCe"<)"mat1!cepti)n which is a subclass of -untime1!cepti)n

C))#ean p 9 new K))#ean'param,.C))#eanRa#ue',E cha" c 9 param.cha"@t'0,E 24

<ut:

2hat#s left3

2e#ve covered enough so far to write simple servlets but not enough to write useful servlets

2e still need to be able to:


0se configuration information Authenticate users Keep trac" of users during a session -etain information across different sessions 7a"e sure our servlets are thread safe Communicate between servlets

<ut remember: The most difficult program in any language is Hello World! 2;

The ,nd

2'