meljun cortes introduction to servlets
TRANSCRIPT
![Page 1: MELJUN CORTES Introduction to Servlets](https://reader031.vdocuments.mx/reader031/viewer/2022021321/577cc58a1a28aba7119cbc52/html5/thumbnails/1.jpg)
8/11/2019 MELJUN CORTES Introduction to Servlets
http://slidepdf.com/reader/full/meljun-cortes-introduction-to-servlets 1/12
TOPIC TITLE: Servlet
SPECIFIC OBJECTIVES:
At the end of the topic session, the students are expected to:
Cognitive :
1. Discuss Common Gateway Interface.2. Explain what a serlet is.!. Compare serlet from Common Gateway Interface "CGI#$. Discuss the %erelt A&I.'. Create a simple serlet.
Affective:
1. &articipate in a (roup actiities2. )e attentie to the teacher*s lectures and demonstrations!. &articipate on class and (roup discussions
Psychomotor:1. Create and deploy serlet.
MATERIALS/EQUIPMENTS:
1. +&2. -opic %lide
TOPIC PREPARATION:
1. eiew of %erlet.
TOPIC PRESENTATION:
-he topic will reole around Servlet. Discussions will include CommonGateway Interface, serlet, context root, we/ application directorystructure and deployment descriptor. .
-his will /e the su((ested flow of discussion for Servlet.
1. Explain what Common Gateway Interface is.2. Discuss the operation o( CGI pro(rams.!. Discuss the adanta(es and disadanta(es o( CGI.$. Explain what serlet is.'. Discuss the adanta(es of serlet.0. Descri/e the life cycle of a serlet.. Discuss the applications that can /e /uilt usin( serlet.. Explain what context root is.3. Explain the we/ application directory structure.14. Discuss the deployment descriptor.
Common Gateway InterfacePage 1 of 8
Common Gatea! Inter"a#e
![Page 2: MELJUN CORTES Introduction to Servlets](https://reader031.vdocuments.mx/reader031/viewer/2022021321/577cc58a1a28aba7119cbc52/html5/thumbnails/2.jpg)
8/11/2019 MELJUN CORTES Introduction to Servlets
http://slidepdf.com/reader/full/meljun-cortes-introduction-to-servlets 2/12
In the early deelopment of -56, desi(ners created a mechanism topermit a user to ino7e a pro(ram on the 8e/ serer. -his was calledthe Cmmon Gateway Interface "CGI#. 8hen a 8e/ site includes CGI
processin(, this is called a 8e/ application.
In order to ino7e the CGI pro(ram, the /rowser sends data to the CGIpro(ram on the 8e/ serer. -he CGI specification defines how thedata is pac7a(ed and sent in the --& re9uest to the serer. -he datais usually typed in into the 8e/ /rowser in an -56 form.
-he 6 determines which CGI pro(ram to execute. -his could /e ascript or an executa/le file. -he CGI pro(ram then parses the data inthe re9uest, process the data and (enerates a response. -his responseis sent /ac7 to the 8e/ /rowser.
$Common Gatea! Inter"a#e% Pa&e ' o" ()
CGI Programs on the WebServer Pages 2! of 8
CGI Pro&ram* on t+e ,e- Server
)elow are the operations of CGI pro(rams.1. )rowser initiates re9uest2. 8e/ serer receies the re9uest.!. ;or each re9uest, we/ serer spawns a new operatin( system
process to execute the CGI<&erl &ro(ram.
-he fi(ure a/oe shows the flow of operations in executin( a CGIpro(ram. At first, the /rowser initiates the re9uest. -he 8e/ serer then responds to that re9uest and it spawns a new opratin( system"+%# process to execute the CGI pro(ram.
At runtime, a CGI pro(ram is launched /y the 8e/ serer as a separateopearatin( system "+%# shell. -he shell includes an +% enironmentand process to execute the code of the CGI pro(ram.
,e-Bro*er
,e-Server
Perl/CGI
Create
New process
Bro*er'
,e-Server
Perl'
Bro*er.
Bro*erN
Perl.
PerlN
![Page 3: MELJUN CORTES Introduction to Servlets](https://reader031.vdocuments.mx/reader031/viewer/2022021321/577cc58a1a28aba7119cbc52/html5/thumbnails/3.jpg)
8/11/2019 MELJUN CORTES Introduction to Servlets
http://slidepdf.com/reader/full/meljun-cortes-introduction-to-servlets 3/12
-he fi(ure a/oe shows that for each re9uest, a separate +% process is/ein( spawned.
oweer, each new CGI re9uest launches a new operatin( system shellon the serer. -he runtime performance of multiple CGI re9uest isshown a/oe.
$CGI Pro&ram* on t+e ,e- Server% Pa&e* .0 o" ()
A"vantages of CGI ProgramsPage # of 8
A1vanta&e* o" CGI Pro&ram*
;lexi/le = &ro(rams can /e written in a ariety of lan(ua(es.
%ta/le = A /u((y CGI pro(ram will not crash the 8e/ serer.
&ro(rams are easy to reference = &ro(rams are easy for a 8e/
desi(ner to reference. 8hen the script is written, the desi(ner canreference it in one line in a 8e/ pa(e.
>o concurrency conflict = )ecause CGI pro(rams execute in their
own +% shell, these pro(rams do not hae concurrency conflictswith other --& re9uests executin( the same CGI pro(ram.
All serice proiders support CGI pro(rams
$A1vanta&e* o" CGI Pro&ram*% Pa&e 2 o" ()
$isa"vantages of CGIProgramsPage % of 8
34*a1vanta&e* o" CGI Pro&ram*
%low
-he response time of CGI pro(rams is ery hi(h /ecause CGIpro(rams execute in their own +% shell. -he creation of an +%shell is a heaywei(ht actiity for the +%.
>ot scala/le
CGI is not scala/le. If the num/er of people accessin( the 8e/application increases from '4 to '444, for example, CGI cannot /e
adapted to handle the load. -here is a limit on the num/er of separate operatin( system processes a computer can run.
>ot secured or o/?ect@oriented
-he lan(ua(es for CGI are not always secure or o/?ect@oriented.
%criptin( lan(ua(es are often platform dependent
-he CGI script has to (enerate an -56 response so the CGI codeis min(led with -56. -his is not (ood separation of presentationand /usiness lo(ic.
)ecause of these disadanta(es, deelopers need other CGIsolutions. %erlets is the aa technolo(y solution used to process
![Page 4: MELJUN CORTES Introduction to Servlets](https://reader031.vdocuments.mx/reader031/viewer/2022021321/577cc58a1a28aba7119cbc52/html5/thumbnails/4.jpg)
8/11/2019 MELJUN CORTES Introduction to Servlets
http://slidepdf.com/reader/full/meljun-cortes-introduction-to-servlets 4/12
CGI data.
$34*a1vanta&e* o" CGI Pro&ram*% Pa&e 5 o" ()
ServletsPage & of 8
Servlet*
A aa serlet is a aa technolo(y pro(ram similar to CGI pro(ram thatruns on the serer. -he types of tas7s that you can run with serlets aresimilar to those you can run with CGI.
A serlet is used to sere serer@side resources to the client. )eforeserlets and its peer technolo(ies such as CGI and Actie %erer &a(eswere introduced, a we/ serer was a/le to sere only static we/ pa(esto the client.
Servlet Ar#+4te#t6re
-he fi(ure a/oe shows the %erlet architecture. nli7e CGI ro(rams,serlets run within a component container architecture. -his container is called the 8e/ container also 7nown as the serlet en(ine. -he 8e/container is a aa irtual machine that supplies an implementation of the serlet application pro(rammin( interface "A&I#. %erlet instancesare components that are mana(ed /y the 8e/ container to respond to--& re9uests.
$Servlet*% Pa&e 7 o" ()
A"vantages of Servlet Page ' of 8
A1vanta&e* o" Servlet
&owerful
%erlets can tal7 directly to the we/ serers.
5ultiple serlets can share data:
&articularly important for maintainin( data/ase connections.
Includes powerful techni9ues for trac7in( user sessions.
&orta/le
CLIENT
WEB
SERVER
Web
Container
SERVLET
DATABASE
Request
Response
![Page 5: MELJUN CORTES Introduction to Servlets](https://reader031.vdocuments.mx/reader031/viewer/2022021321/577cc58a1a28aba7119cbc52/html5/thumbnails/5.jpg)
8/11/2019 MELJUN CORTES Introduction to Servlets
http://slidepdf.com/reader/full/meljun-cortes-introduction-to-servlets 5/12
Bou can therefore write your serlets on 8indows, then deploy them
on >I. Bou can also run any of your serlets on any aa@ena/led we/
serer, with no code chan(es.
%ecure
-raditional CGI pro(rams hae a num/er of 7nown security
ulnera/ilities. ence, you usually need to include a separate &erl<CGI module to
supply the necessary security protection. aa has a num/er of /uilt@in security layers.
ence, serlets are considered more secure than traditional CGI
pro(rams.
Inexpensie
Bou can download free serlet 7its for deelopment use.
Bou can therefore (et started for free
>onetheless, production stren(th serlet we/ serers can (et 9uite
expensie.
$A1vanta&e* o" Servlet% Pa&e 8 o" ()
(ife of a Servlet Page 8) of 8
L4"e o" a Servlet
e(ardless of the application, serlets usually carry out the followin(
routine:
1. ead any data sent /y the user 2. 6oo7 up any --& information!. Generate the esults$. ;ormat the esults'. %et the Appropriate --& headers0. %end the document /ac7 to the client
Servlet Pro&ram Ro6t4ne
$L4"e o" a Servlet% Pa&e (9 o" ()
,e-Bro*e
r
,e-Server
3ata
-a*e 3
6Java
Servlet
,e-Bro*e
r
,e-Server
3ata
-a*e
4,5Java
Servlet
,e-Bro*er
,e-Server
3ata-a
*e
1,2
Java
Servlet
![Page 6: MELJUN CORTES Introduction to Servlets](https://reader031.vdocuments.mx/reader031/viewer/2022021321/577cc58a1a28aba7119cbc52/html5/thumbnails/6.jpg)
8/11/2019 MELJUN CORTES Introduction to Servlets
http://slidepdf.com/reader/full/meljun-cortes-introduction-to-servlets 6/12
What can yo* b*il" withServlets+Page 1, of 22
,+at #an !o6 -64l1 4t+ Servlet*
Search -ngines
Personaliation Systems -Commerce A//lications
Sho//ing Carts
Pro"*ct Catalogs
Intranet A//lications
Gro*/ware A//lications: b*lletin boar"s0 file sharing0 etc.
$,+at #an !o6 -64l1 4t+ Servlet*% Pa&e '; o" ';)
Contet oot Page 11 of 22
Conte<t Root
Eery we/ application has a uni9ue context root
-he context root forms a part of the re9uest 6
-he container maps a re9uest to the correspondin( application
/ased on the context root
Example, consider an application called 6o(inApplication, the
6 will /e
htt/:33www.myA//s.com3login3(oginServlet
-he context root is also called as the 8e/ application context name. Itis part of the 6 you use to access a 8e/ application. It is the first
leel of hierarchy in the path structure of the 6. -he (eneral syntaxof a serlet 8e/ application 6 is:
http://host:port/context/path/file
where context is the 8e/ application context name.
Examples:
≠ http:<<www.sti.edu.ph<enrolment<admin.html≠ http:<<www./as7et/all.or(<lea(ues<re(istration.html
$Conte<t Root% Pa&e '; o" ';)
Web A//lication $irectoryStr*ct*rePage 12 of 22
,e- A==l4#at4on 34re#tor! Str6#t6re
![Page 7: MELJUN CORTES Introduction to Servlets](https://reader031.vdocuments.mx/reader031/viewer/2022021321/577cc58a1a28aba7119cbc52/html5/thumbnails/7.jpg)
8/11/2019 MELJUN CORTES Introduction to Servlets
http://slidepdf.com/reader/full/meljun-cortes-introduction-to-servlets 7/12
-he directory structure for we/ applications is (ien in the fi(ure a/oe.
e-A==l4#at4on = holds the contents of the 8e/ Application Archie"8AR # file that will /e deployed to the serer It contains all the we/resources, includin( -56 files, %&s and (raphics needed for theapplication.
e-A==l4#at4on/t+eme = contains cascadin( style sheets and other style@related o/?ects.
e-A==l4#at4on/4ma&e* = contains ima(es used /y the application
e-A==l4#at4on/,EBINF = contains the supportin( we/ resources for a we/ application, includin( the we/.xml deployment descriptor file, theclasses and li/.
e-A==l4#at4on/,EBINF/#la**e* = it the aa compiler outputdirectory. It contains all the class files pertainin( to the we/ application.-he application class loader loads the classes from this directory.
e-A==l4#at4on/,EBINF/l4- = contains the .?ar files that the we/application references. Any classes contained in these .?ar files will /eaaila/le for the we/ application.
$,e- A==l4#at4on 34re#tor! Str6#t6re% Pa&e '. o" ';)
![Page 8: MELJUN CORTES Introduction to Servlets](https://reader031.vdocuments.mx/reader031/viewer/2022021321/577cc58a1a28aba7119cbc52/html5/thumbnails/8.jpg)
8/11/2019 MELJUN CORTES Introduction to Servlets
http://slidepdf.com/reader/full/meljun-cortes-introduction-to-servlets 8/12
$e/loyment $escri/tor Page 1! of 22
3e=lo!ment 3e*#r4=tor
Deployment descriptor is a file containin( deployment
information
-he we/ container reads it durin( the deployment of the
we/ application onto the we/ serer
2EE compliant we/ containers use an 56 file called
e-><ml as the deployment descriptor
-he deployment descriptor is a file containin( deployment information.2EE compliant we/ containers use an 56 file called the we/.xml asthe deployment descriptor. -he Document -ype Definition "D-D# for thewe/.xml file is specified /y the aa %erlet specification. It is an 56file which contains names of arious serlets in the we/ application, the
6 mappin(s for each serlet, security information and other deployment information.
$3e=lo!ment 3e*#r4=tor% Pa&e '0 o" ';)
Servlet Class 4ierarchy Page 1# of 22
Servlet Cla** ?4erar#+!
All the serlets inherits from the class --&%erlet. -he --&%erletin turn inherits from the Generic%erlet class and the Generic%erletclass implements the %erlet interface.
-he %erlet interface specifies the methods that the container willino7e on the serlet. -he interface forms a contract /etween the we/container and the serlet. All the serlets therefore hae to directlyimplement the %erlet interface. -he interface defines the init"#,serice"#, and destroy"# methods used /y the container for mana(in(the life cycle of the serlet.
-he Generic%erlet class is an a/stract class that proides a /asic
implementation of the %erlet interface. %erlets inheritin( from thisclass can use the implementation it has proided for all the methods of
ServletServlet
HTTPServletHTTPServlet
Generic ServletGeneric Servlet
![Page 9: MELJUN CORTES Introduction to Servlets](https://reader031.vdocuments.mx/reader031/viewer/2022021321/577cc58a1a28aba7119cbc52/html5/thumbnails/9.jpg)
8/11/2019 MELJUN CORTES Introduction to Servlets
http://slidepdf.com/reader/full/meljun-cortes-introduction-to-servlets 9/12
the serlet interface except the serice"# method.
-he ttp%erlet class proides --&@specific implementation of the
%erlet interface. -he ttp%erlet class oerrides the serice"# methodit inherits from the Generic%erlet. -he ttp%erlet class is an a/stractclass and all classes inheritin( from this class should proide either thedoGet"# or do&ost"# methods. Dependin( on the --& methodssupported /y the application, the pro(rammer should proideimplementation for the correspondin( doxx"# method in the serlet.
$Servlet Cla** ?4erar#+!% Pa&e '2 o" ';)
Creating Servlet Page 1%18 of 22
Creat4n& Servlet
6isted /elow are the steps in creatin( a serlet.
1. Import the %erlet A&I:
import ?aax.serlet.Fimport ?aax.serlet.http.F
-o create serlets, you must remem/er to always use these two importstatements. All your serlets must extend --&%erlet.
2. --&%erlet represents the /ase class for creatin( %erlets withinthe %erlet A&I. -herefore, you must extend the--&%erlet class.
!. +nce you hae extended --&%erlet, you must oerride one or
/oth:o doGet"#: to capture --& Get e9uests
o do&ost"#: to capture --& &ost e9uests
-he doGet"# and do&ost"# methods each ta7e two parameters: --&%erlete9uest: encapsulates all information
re(ardin( the /rowser re9uest such as form data, clienthost name, --& re9uest headers.
--&%erletesponse: encapsulates all information
re(ardin( the serlet response such as --& eturnstatus, out(oin( coo7ies, -56 response.
If you want the same serlet to handle /oth GE- and &+%-,you can hae doGet call do&ost or ice ersa. se GE-re9uest if the amount of form data is small and you want toallow the re9uest to /e /oo7mar7ed. se &+%- re9uest if youwant to modify the serer "data/ase#, the amount of form datais lar(e and the contents of the form data should not /e isi/lein the re9uest 6.
$. Gettin( an +utput%tream
-he --&esponse o/?ect has a (et8riter"# method that allows
you to print out data. -his method returns a ?aa.io.&rint8ritero/?ect for writin( data out to the 8e/ )rowser.
&rint8riter out response.(et8riter"#F
![Page 10: MELJUN CORTES Introduction to Servlets](https://reader031.vdocuments.mx/reader031/viewer/2022021321/577cc58a1a28aba7119cbc52/html5/thumbnails/10.jpg)
8/11/2019 MELJUN CORTES Introduction to Servlets
http://slidepdf.com/reader/full/meljun-cortes-introduction-to-servlets 10/12
+nce you hae an +utput%tream o/?ect, you ?ust call the println"#method to output to the /rowser. Anythin( you print will display
directly within the we/ /rowser.
out.println" HInalid ID >um/er @ Diision /y ero ErrorJnH #F
Example:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServletTemplate extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, !Exception {
rint!riter out " response.#et!riter();
"
"
-he example a/oe shows a simple serlet. It does nothin( /ut it showsthe /asic re9uirement for a serlet to /e executed properly such as theimport statement for the serlet, the doGet implementation and the useof the (et8riter"# method.
$Creat4n& Servlet% Pa&e '5'( o" '0)
Case St*"y Page 1)22 of 22
Ca*e St61y
Bour school administrator has as7ed your (roup to come up with apro(ram to implement the new username al(orithm for all students oncampus. e will proide the first name, last name, and an ei(ht@di(it idnum/er that will /e used in the creation of the user name.
-he proposed user name will /e the first three characters of the lastname followed /y the last three characters of the first name. +nce thetext portion is completed, the user name will contain a four@di(it num/er.-he four@di(it num/er is the last six di(its of the id num/er diided /ythe first two di(its. In the eent the first name or last name is less than
! characters, use all aaila/le characters and do not add any extraspace.
-he first two num/ers to the id num/er should /e chec7ed for diide /yKero errors and any diision should use inte(er diision "truncate thedecimal point#. -he first name and last name will not exceed 2''characters. -he pro(ram should continue to input data until a L@1M isproided.
%ample Inputoe%mith4!$44!2
%ample +utput:
![Page 11: MELJUN CORTES Introduction to Servlets](https://reader031.vdocuments.mx/reader031/viewer/2022021321/577cc58a1a28aba7119cbc52/html5/thumbnails/11.jpg)
8/11/2019 MELJUN CORTES Introduction to Servlets
http://slidepdf.com/reader/full/meljun-cortes-introduction-to-servlets 11/12
%mioe$'
%olution:
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class #ser$ame exten%s
javax.servlet.http.&ttpServlet {
public voi% %o'et(&ttpServlet)euest re,
&ttpServlet)esponse resp+
throws !Exception, ServletException {
Strin tTemp - , t!utput - ;
lon lower - 0, l#pper1 - 0;
Strin t2irst$ame - re.et3arameter(fname+;
Strin tast$ame - re.et3arameter(lname+;
lon l4$umber -
nteer.parsent(re.et3arameter(i%++;
3rint5riter out-resp.et5riter(+;
tTemp - tast$ame.substrin(0,6+;
t!utput - tTemp;
if ( t2irst$ame.lenth(+ 7- 6 +
tTemp -t2irst$ame.substrin(t2irst$ame.lenth(+8
6,t2irst$ame.lenth(+ +;
else
tTemp - t2irst$ame;
//mo%ulus
lower - l4$umber 9 000000;
//inteer %ivision
l#pper1 - l4$umber / 000000;
out.println(html7+;
out.println(bo%<7+;
out.println(h7+;
if ( l#pper1 -- 0 +{
out.println( nvali% 4 $umber 8
4ivision b< =ero Error>n +;
"
else{
out.println(#sername: ?t!utput?tTemp?((
lower / l#pper1 + 9 0000++;
"
out.println(/h7+;
out.println(/bo%<7+;
out.println(/html7+;
"
public voi% %o3ost(&ttpServlet)euest re,
&ttpServlet)esponse resp+
![Page 12: MELJUN CORTES Introduction to Servlets](https://reader031.vdocuments.mx/reader031/viewer/2022021321/577cc58a1a28aba7119cbc52/html5/thumbnails/12.jpg)
8/11/2019 MELJUN CORTES Introduction to Servlets
http://slidepdf.com/reader/full/meljun-cortes-introduction-to-servlets 12/12
throws !Exception, ServletException {
%o'et(re, resp+;
"
" // en% of class #ser$ame
-o (enerate -56, you need to add two steps:
-ell the /rowser that you are sendin( /ac7 -56.
5odify the println"# statements to return alid -56.
html7
hea%7/hea%7
bo%<7
&7#ser $ame 'enerator/&7
form action-user metho%-post7
2irst $ame:
input t<pe-text name-fname 7
ast $ame:input t<pe-text name-lname 7
#ser 4:
input t<pe-passwor% name-i% 7
input t<pe-submit value-3rocess7
/form7
/bo%<7
/html7
$Ca*e St61!% Pa&e '9.. o" ';)
EVALUATION/GENERALI@ATION
1. Explain what serlet is.2. Identify and discuss the adanta(es of serlet oer CGI.
REFERENCES
o %ams -each Bourself aaN 2 in 21 Days, ;ourth
Edition /y o(ers Cadenhead, 6aura 6emay
o ust aaN 2 %I- EDI-I+>
/y &E-E an der 6I>DE>
o -he aa -utorial @ An excellent collection of on@linefrom %> 5icrosystems"http:<<?aa.sun.com<docs</oo7s<tutorial<#
o aa 2 'th Ed. -he Complete eference
/y er/ert %childt