Servlets Basic Operations

indexadjustmentInternet και Εφαρμογές Web

13 Νοε 2013 (πριν από 3 χρόνια και 8 μήνες)

74 εμφανίσεις

1
Servlets
Basic Operations
Michael B. Spring
Department of Information Science and Telecommunications
University of Pittsburgh
spring@imap.pitt.edu
http://www.sis.pitt.edu/~spring
September 28, 2001 Introduction to Servlets 2
Overview
• Preparing to develop servlets on your PC
• Writing and running an “Hello World” servlet
• Servlet Basics
• The Servlet API
• Loading and Testing Servlets
2
September 28, 2001 Introduction to Servlets 3
Preparing your System
• Locate the file “jswdk1_0_1-win.zip”
• Using winzip, extract all the files to the JDK directory. By default the
directory will be “j dk.1.2.2”
• Set an environment variable called JAVA_HOME to the JDK directory for
JDK. Use a fully qualified (complete) pathname in setting the variable
• I n NT, r i ght c l i c k on my c omput er, s el ec t t he envi r onment t ab, and a l l a ne w
e nvi r onme nt var i abl e and val ue
• I n Wi n 95/98, e di t t he aut oe xe c.bat f i l e t o i nc l ude t he c ommand “set
J AVA_ HOME p a t h ”
• Add the full path (including filename) of the servlet.jar file in the jswdk-
1.0.1/lib subdirectory to your CLASSPATH variable definition
September 28, 2001 Introduction to Servlets 4
Preparing your
System(continued)
• In the subdirectory jswdk-1.0.1, you will find two batch files:
• startserver.bat is used to start a local servlet server
• stopserver.bat is used to stop the local servlet server
• If double clicking on the startserver.bat file doesn’t work, run
a DOS window and issue the command manually.
• Using Netscape or Internet Explorer, specify the following
location – http://localhost:8080/
• If you have followed the directions, you will get a page with a
set of sample servlets and java server pages.
3
September 28, 2001 Introduction to Servlets 5
A Simple A Simple ServletServlet
September 28, 2001 Introduction to Servlets 6
A Simple Servlet
• Servlets are basically Java programs that do input and output in response
to contact from web servers.
• Servlets have several advantages over CGI scripts which will be
addressed in time.
• For now we look at the structure of a simple servlet.
• I mpor t t he c or r e c t pac kage s
• Ext e nd t he Ht t pSer vl et c l a s s f r om t he pa c ka ge, ove r wr i t i ng f our me t hods
• “i ni t ” t o s et r es our c es
• “ s e r vi c e ” t o pr ovi de t he ba s i c s e r vi c e
• “ get Ser vl et I nf o ” t o pr ovi de a de s c r i pt i on of t he s er vl et t o t he s er ver – t he
des c r i pt i on i s a s t r i ng
• “ de s t r oy” t o f r e e a ny a l l oc a t e d r e s our c e s
4
September 28, 2001 Introduction to Servlets 7
The Code for the Servlet
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.PrintWriter;
import java.io.IOException;
// a simple servlet
public class simpservlet extends HttpServlet
{
public void init(ServletConfig config)throws ServletException
{super.init(config);//just accept the parent init}
public void service(HttpServletRequest req, HttpServletResponse
rsp)
throws ServletException,IOException
{String ms[]={"one","two","three","four","five"};
rsp.setContentType("text/html");
PrintWriter out = rsp.getWriter();
out.println("<HTML><HEAD><TITLE>Simple</TITLE></HEAD><BODY>");
for (int i=1;i<=5;i++)
{out.println("<P>"+i+". This is line " +ms[i-1]);}
out.close();}
public String getServletInfo(){return "A little demo";}
public void destroy(){ //free resources}
}
September 28, 2001 Introduction to Servlets 8
How the Servlet works
• The HTTPServlet class is constructed to minimize the amount
of effort you need to put into a client server exchange
• Note that the service method provides both a request and a
response.
• The request consists of a header and a potentially a body neither of
which we will deal with here
• The response will also consist of a header and a body. The superclass
will take care of most of that for us, but we will need to ident ify the
ContentType of the response, and there is a method to allow us to do
that.
• Finally, we can obtain access to an IOStream that will allow us to
specify the body of the message. When done we simply close the
stream
5
September 28, 2001 Introduction to Servlets 9
Positioning/Running a Servlet
• For the purposes of this demo, we will not do any further
adjustments of the CLASSPATH, but adjustments will be
required for more complex servlets and for JSPs
• Compile the Java servlet provided as exercise 1.
• Copy the class file to the following subdirectory of the JDK
directory:
• j s wdk- 1.0.1\exampl es\WEB- I NF\ser vl et s\
• Start up the servlet test engine using the batch file in jswdk-
1.0.1
• Run Netscape or Internet Explorer using the following URL:
• ht t p://l ocal host:8080/exampl es/ser vl et/si mpser vl et
September 28, 2001 Introduction to Servlets 10
Positioning and Running Servlets
JDK directory
JSWDK
directory
Place any servlets created in
jswdk-1.0.1/examples/Web-inf/servlets
Create a directory
jswdk-1.0.1/webpages/dtp
For html pages to invoke servlets
6
September 28, 2001 Introduction to Servlets 11
An Exercise
• Produce a new servlet based on the example provided above.
• The ideal servlet for this first example will do three things:
• Expand the string array to specify sayings, tips, or fortunes and select one
based on a random number function for display.
• Present a result document that includes a form with at least a
listbox(<SELECT> and <OPTION> and a submit button.
• The l i s t box wi l l i nc l ude as opt i ons s ome numbe r of i t e ms t hat a pe r s on mi ght
wa nt t o buy.
• You c a n s ubmi t t he f or m t o a dummy URL.
• The f or m s houl d be a “ge t ” me t hod s o you c an s e e t he ar gume nt s o n t he
r equest
September 28, 2001 Introduction to Servlets 12
ServletServlet BasicsBasics
7
September 28, 2001 Introduction to Servlets 13
Rationale for Servlets
• Can be run as threads in the server process requiring less
startup overhead.
• They can be started at server start saving more time
• As bytecodes, servlets generally run faster than scripts
• While slower than binaries, they are more robust, operate
cross platform, and cross server
• While servlets support http by explicit subclass, they are
protocol independent by design
• They extend the capability and range of Java code bases and
expertise.
September 28, 2001 Introduction to Servlets 14
Servlet Basics
• The servlet lifecyle (init, service, destroy) is as follows:
• Load ( at s er ver s t ar t up or at f i r s t r eques t ) and i ns t ant i at e one or mor e c opi e s
• Cr e at e s a Se r vl e t Conf i g obj e c t
• Pas s t he S e r vl e t Conf i g obj ec t t o eac h i ni t pr oc es s
• The s er ver pr oc es s es a r eques t ( s )
• For mi ng r e que s t a nd r e s pons e obj e c t s ba s e d on t he c onne c t i on
• Ca l l i ng t he s e r vi c e me t hod pa s s i ng t he s e obj e c t s ( The s e r vi c e met hod wi l l be
e xpande d t o s pe c i f i c s e r vi c e s )
• The s e r vi c e e xami ne s t he r e que s t, e i t he r di r e c t l y or i ndi r e c t l y( ba s e d on t he
s pe c i f i c s e r vi c e c a l l e d) a nd f or mul a t e s a r e s pons e pa s s e d t hr ough t he r e s pons e
obj ect
• The s er ver unl oads t he s er vl et when di r ec t ed t o do s o and c al l s t he de t r oy
me t hod
8
September 28, 2001 Introduction to Servlets 15
The Load/Service Relation
• This servlet will count the number of hits
public class countservlet extends HttpServlet
{static int NReq=0;
public void service(HttpServletRequest req,
HttpServletResponse rsp) throws
ServletException,IOException
{rsp.setContentType("text/html");
PrintWriter out = rsp.getWriter();
NReq++;
out.println("<HTML><HEAD><TITLE>”)
out.println(“Counted Request</TITLE></HEAD><BODY>");
out.println("<P>Reuest" + NReq + "since start</P>");
out.println("</BODY></HTML>");
out.close();}
September 28, 2001 Introduction to Servlets 16
The The Servlet Servlet APIAPI
9
September 28, 2001 Introduction to Servlets 17
The Servlet API
• The servlets are derived as follows:
java.lang.Object
javax.servlet.GenericServlet
javax.servlet.http.HttpServlet
• This discussion focuses primarily on the http servlet, but it
should be made clear that there is also a protocol neutral
servlet
• The HttpServlet class is supported by an HttpServletRequest
interface and the HttpServletResponse interface. (the generic
class has similar interfaces)
• The HttpServlet class is an abstract class – it must be extended
September 28, 2001 Introduction to Servlets 18
Methods required for the
HttpServlet
• The methods init(), service(), and destroy() have been
discussed. The service method normally passes the request to
a specific methods – each of which responds to one of the
htttp protocols
• In the examples to date, the overridden service method has
provided a monolithic response – which might be very
confusing to the client
• Some additional methods exist for communication between
theservlet and server, one example being getServletInfo()
which has been previously discussed
10
September 28, 2001 Introduction to Servlets 19
Specific HTTP Methods
• doGe t ( ) r e s ponds t o nor mal ht t p r e que s t s ( GET) and f or ms ac t i ons s ubmit t ed wi t h t he
GET me t hod
• d o He a d( ) r e s ponds t o t he ht t p HEAD r e que s t whi c h as ks f or he ade r i nf or mat i on
about a f i l e – t ype, si ze, l ast modi f i cat i on dat e, et c.
• doPos t ( ) r e s ponds t o t he POST r e que s t whi c h i nc l ude s f or m i nf or mat i on i n t he body
of t he r eques t
• do Put ( ) r e s ponds t o t he PUT r e que s t whi c h i nc l ude s a doc ume nt t o be st or ed on t he
s e r ve r i n t he body and pl ac e me nt and aut hor i zat i on i nf or mat i on i n t he he a de r.
• doDel et e( ) r e s ponds t o t he DELETE r e que s t whi c h r e move s a doc ume nt gi ve n
appr opr i at e aut hor i zat i on.
• doTr ac e ( ) r e s ponds t o t he TRACE r e que s t whi c h i s us e d f or di agnos t i c pur pos e s – i t
s ends t he ent i r e r eques t bac k as t he body of t he r es pons e.
• do Opt i o n s( ) r e s ponds t o t he OPTI ONS r e que s t whi c h i s us e d t o as k a s e r ve r what
ki nds of met hods t he s er ver wi l l r es ponds t o.
September 28, 2001 Introduction to Servlets 20
Http Headers
• The htttp message header has a number of lines
• The first line takes the form
• G E T ( o r P U T o r P O S T ) p a t h/f i l e n a m e H T T P/1.1
• The other headers are related among other things to
• Sec ur i t y and aut hent i c at i on
• Cont e nt
• Cl i e nt Ca pa bi l i t y
• The content headers include:
• Cont e nt - Type: The mi me t ype of t he body
• Cont e nt - Enc odi ng: Addi t i onal c odi ng be yond t hat as s ume d f or t he Type
• Cont e nt - Lengt h: t he s i ze of t he body, whet her or not i t i s r et ur ned
11
September 28, 2001 Introduction to Servlets 21
HttpServletRequest Interface
• The HttpServletRequest Interface has several methods. The more
interesting of these methods include:
• g e t He a de r Na me s( ) r e t ur ns a n Enume r a t i on of t he me s s a ge he a de r s
• ge t He ade r ( St r i ng na me ) r e t ur ns t he va l ue of t he na me d he a de r
• get i nt Header ( St r i ng na me ) r e t ur ns t he va l ue of t he na me d he a de r a s a n
i nt eger – or –1 i f i t does not exi st
• g e t Re mo t e Us e r( ) r e t ur ns t he us e r name s ubmi t t e d by ht t p aut he nt i c at i on
( when a s er ver r eques t s aut hent i c at i on, t he c l i ent, i f enabl ed, r es ponds wi t h
an “Aut hor i zat i on:” he ade r i n t he ne xt and s ubs e que nt r e que s t s t hat
pr ovi des t he dat a nec es s ar y t o aut hent i c at e t he us er.
• ge t Que r yS t r i ng( ) r et ur ns t he r aw s t r i ng of par amet er s and val ues pas s ed
f r om t he s er ver t o t he servl et
September 28, 2001 Introduction to Servlets 22
ServletRequest Interface
• The HttpServletRequest Interface inherits all of the methods of the
ServletRequest Interface
• Several of the ServletRequest methods are of import
• ge t Re a de r( ) r et ur ns a Buf f e r e dRe ade r we c a n us e t o r e a d t he body
• ge t Re mot e Hos t ( ) r et ur ns t he c l i ent ’ s f ul l y qual i f i ed name as a s t r i ng
• ge t Par ame t e r ( St r i ng name ) r e t ur ns t he val ue of t he s pe c i f i e d par ame t e r.
Be war e t hat t hi s i s dange r ous i f t he par ame t e r al l ows mul t i pl e val ue s as
mi ght be t he cas e i n a s el ect.
• g e t Pa r a me t e r Na me s( ) whi c h r e t ur ns a n Enume r a t i on of pa r a me t e r na me s
• ge t Pa r a me t e r Va l ue s( ) whi c h r et ur ns an ar r ay of s t r i ngs
• Par ame t e r s, ar e t he val ue s f r om t he GET or POST r e que s t al r e ady par s ed.
12
September 28, 2001 Introduction to Servlets 23
HttpServletResponse Interface
• The HttpServletResponse Interface has a number of methods. Among the
more centeral and interesting are:
• s e t He ade r ( St r i ng name, St r i ng val ue ) whi c h s e t s t he he ade r of t he name
g i v e n wi t h t h e v a l u e s p e c i f i e d. C a r e s h o u l d b e t a k e n a s t h e
val i dat e t he c or r e c t f or m of t he he ade r or val ue
• s endEr r or ( i nt s t at us c ode) s ends an er r or mes s age ( i n c ont r as t t o t he
s t andar d Ok ( 200) c ode. Def i ned val ues i nc l ude:
• S C _ B AD_ R E QUE S T – ba d s ynt a x i n r e que s t
• S C_ CONF L I CT – c onf l i c t i n a c c e s s i ng r e s our c e
• S C_ F OR B I DDE N – r e f us al t o pr ovi de ac c e s s
• S C _ GONE – r e s our c e i s no l onge r he r e
September 28, 2001 Introduction to Servlets 24
ServletResponse Interface
• The HttpServletResponse Interface inherits all of the methods of the
ServletResponseInterface
• There are only four ServletResponsemethods, but they are all important
• get Wr i t er ( ) r et ur ns a Pr i nt Wr i t er whi c h s uppor t a pri nt l n ( ) me t hod t hat c an
be us ed t o pr i nt t ext out put
• s e t Cont e nt Le ngt h( i nt l engt h) i s cr i t i cal f or set t i ng t he Cont e nt Le ngt h: header
of t he r es pons e, wi t hout whi c h t he c l i ent wi l l i gnor e t he body of t he r e t ur n
me s s a ge
• s e t Cont e nt Type ( St r i ng name) i s cr i t i cal i n def i ni ng f or t he cl i ent t he mi me
t ype of t he body of t he mes s age
• ge t Out put S t r e a m( ) r et ur ns a S e r vl e t Out put S t r e a m whi c h i s us e d pr i mar i l y
t o s uppor t t he wr i t i ng of bi nar y dat a – s uc h a s a n i ma ge.
13
September 28, 2001 Introduction to Servlets 25
Loading and Running Servlets
• The f i r s t s t ep i n l oadi ng a s er vl et i s t o wr i t e and c ompi l e t he s er vl et
• Be s ur e t hat your CLASSPATH var i abl e i nc l ude s t he f ul l y qual i f i e d f i l e na me
( dr i ve:\pat h\s er vl et.j ar ) f or t he servl et.j ar f i l e
• Move t he c ompi l e d cl assf i l e t o t he di r ec t or y wher e s e r vl e t s ar e s t or ed by def aul t
dr i ve:\J D K L O C A T I O N\j s wd k -1.0.1\e x a mpl e s\WE B -I N F\s e r vl e t s\
• St ar t t he J SDK s er vl et r unne r us i ng t he st ar t ser ver.bat f i l e i n j s wd k- 1.0.1
• St ar t your br ows er and s pec i f y t he name of t he s er vl et us i ng t he f ol l owi ng:
ht t p://l o c a l ho s t:8 0 8 0/e x a mpl e s/s e r vl e t/c l a s s f i l e na me
• I f you have s t ar t ed t he J SDK Ser vl et Runner on a mac hi ne ac c es s i bl e t o t he i nt er net
you may al s o ac c es s t he s er vl et f r om ot he r mac hi ne s by s pe c i f yi ng t he domai n name
of ip addr e s s of t he mac hi ne r unni ng t he Ser vl et Runner.
September 28, 2001 Introduction to Servlets 26
More on Servlet Runner
• Location of normal HTML files
drive:\JDKLOCATION\jswdk-1.0.1\webpages\
Directory depth may be develop as you see fit
• Changing parameters
• Accessing drive:\JDKLOCATION\jswdk-1.0.1\webserver.xml
• Reloading servlets
• Need to restart the server
• Using the console for output
• Use of System.out.println()
14
September 28, 2001 Introduction to Servlets 27
Debugging a Servlet
• Many IDEs provide debugging capabilities –
including debugging for servlets
• FreeJava offers no direct support for debugging
• You can achieve crude debugging by
• Including System.out.println() in your source
• Watching the results in the Servlet Runner Console
September 28, 2001 Introduction to Servlets 28
Exercise
• Bui l d t wo ser vl et s.
• Ser vl et one wi l l be a r evi si on of t he s er vl et you pr oduc e d i n t he pr e vi ous e xe r c i s e. The
Ser vl et wi l l pr oduc e a f or m t hat has f i ve t ext i nput s, t wo s et s of r adi o but t ons and t wo
sel ect boxes.
• On e s e l e c t wi l l b e t e n l i n e n p r o d u c t s ( f a c e c l o t h, b a t h t o we l, s h e e t, e t c ) a n d t h e o t h e r
c ol or
• T h r e e t e x t i n p u t s w i l l b e: N a m e, S t r e e t A d d r e s s, a n d C i t y,
• O n e R a d i o b u t t o n i n p u t s w i l l b e f o r c r e d i t c a r d t y p e
• T wo t e x t i n p u t s wi l l b e C r e d i t C a r d Nu mb e r a n d E x p i r a t i o n d a t e
• T h e S e c o n d R a d i o B u t t o n i n p u t w i l l b e d e l i v e r y m o d e
• T h e s e c o n d s e r v l e t wi l l pr oc es s t he f or m r et ur n. I t wi l l us e t he doPos t or doGe t
i n a c c o r d w i t h h o w y o u w r i t e t h e f o r m p r o d u c e d b y t h e f i r s t
r e s e n d t h e f o r m p a r t i a l l y f i l l e d o u t i f t h e r e i s m i s s i n g d a t a, o r i t wi l l
d i s p l a y p a g e c o n f i r m i n g t h e u s e r s s e l e c t i o n a n d t h a n k i n g t h e m i f al l