Você está na página 1de 3

1

21-Nov-11
Servlets
2
Servers
A serverisacomputer that respondsto requestsfromaclient
Typical requests: provide awebpage, upload or download afile, send
email
A serverisalso thesoftwarethat respondsto theserequests; a
clientcouldbethebrowser or other softwaremaking these
requests
Typically, your littlecomputer istheclient, andsomeoneelses
bigcomputer istheserver
However, any computer canbeaserver
It is not unusual to have server software and client software running onthe
same computer
3
Apache
Apacheis avery popular server
66% of thewebsitesontheInternet useApache
Apacheis:
Full-featuredandextensible
Efficient
Robust
Secure(atleast, moresecurethanother servers)
Upto datewithcurrentstandards
Opensource
Free
Why useanythingelse?
4
Ports
A portisaconnectionbetweenaserver andaclient
Ports areidentified by positive integers
A port is asoftware notion, not ahardware notion, sothere may bevery
many of them
A serviceisassociatedwithaspecific port
Typical port numbers:
21FTP,File TransferProtocol
22SSH, SecureShell
25SMTP,Simple Mail TransferProtocol
53DNS,DomainNameService
80HTTP, Hypertext Transfer Protocol
8080HTTP (used for testing HTTP)
7648, 7649CU-SeeMe
27960QuakeIII
These arethe ports
of most interest tous
5
Ports II
MyUPenn Webpageis:
http://www.cis.upenn.edu/~matuszek
But itisalso:
http://www.cis.upenn.edu:80/~matuszek
Thehttp: atthebeginningsignifiesaparticular protocol
(communication language), theHypertext Transfer Protocol
The:80 specifiesaport
Bydefault, theWebserver listensto port80
The Webserver could listen toany port it chose
This could lead to problems if the port was in use bysome other server
For testing servlets, wetypically have the server listen toport 8080
InthesecondURL above, I explicitlysent my requestto port80
If I had sent it to some other port, say, 99, my request would either go
unheard, or would (probably) not beunderstood
6
CGI Scripts
CGI stands for Common Gateway Interface
Client sends arequest to server
Server starts aCGI script
Script computes aresult for server
and quits
Another client sends arequest
client server
client
script
Server starts the CGI script again
Etc.
script
Server returns response toclient
7
Servlets
A servlet is likean applet, but on theserver side
Client sends arequest to server
Server starts aservlet
Servlet computes aresult for
server and does not quit
Another client sends arequest
client server
client
servlet
Server calls the servlet again
Etc.
Server returns response toclient
8
Servlets vs. CGI scripts
Advantages:
Running aservletdoesntrequirecreatingaseparateprocess
eachtime
A servletstays inmemory, so itdoesnthaveto bereloaded
eachtime
Thereisonlyoneinstancehandlingmultiplerequests, not a
separateinstancefor everyrequest
Untrusted servletscanberuninasandbox
Disadvantage:
Lesschoiceof languages (CGI scriptscanbeinany language)
9
Tomcat
Tomcat istheServletEngine thanhandlesservletrequests
for Apache
Tomcat is ahelper application for Apache
Its best to think of Tomcat asaservlet container
Apachecanhandlemany typesof webservices
Apache canbeinstalled without Tomcat
Tomcat canbeinstalled without Apache
Itseasier to install Tomcat standalonethanaspartof
Apache
By itself, Tomcat canhandle webpages, servlets, andJSP
ApacheandTomcat areopensource(andthereforefree)
2
10
Servlets
A servlet is any class that implements the
javax.servlet.Servlet interface
Inpractice, most servletsextend the
javax.servlet.http.HttpServlet class
Someservletsextendjavax.servlet.GenericServlet instead
Servlets, likeapplets, usually lack amain method, but
must implement or overridecertain other methods
11
Important servlet methods, I
Whenaservletisfirststartedup, itsinit(ServletConfig config)
method iscalled
init should performany necessary initializations
init is called only once, and does not need to bethread-safe
Everyservletrequestresultsinacall to
service(ServletRequest request, ServletResponse response)
service calls another method depending onthe 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
Whentheservletisshut down, destroy() iscalled
destroy is called only once, but must bethread safe (because other threads
may still berunning)
12
HTTP requests
WhenarequestissubmittedfromaWebpage, itisalmostalways
aGETor aPOST request
TheHTTP <form> taghasanattributeaction, whosevaluecan
be"get" or "post"
The"get" actionresultsintheforminformationbeingput after a
? intheURL
Example:
http://www.google.com/search?hl=en&ie=UTF-8&oe=UTF-
8&q=servlets
The & separates the various parameters
Only alimited amount of information canbesent this way
"put" cansendlargeamounts of information
13
Important servlet methods, II
Theservicemethoddispatchesthefollowingkinds of requests:
DELETE, GET, HEAD, OPTIONS, POST, PUT, andTRACE
A GET request is dispatched to the doGet(HttpServletRequest request,
HttpServletResponse response) method
A POST request is dispatched to the doPost(HttpServletRequest
request, HttpServletResponse response) method
These arethe two methods youwill usually override
doGet and doPost typically dothe same thing, sousually youdo the real
work in one, and have the other just call it
public void doGet(HttpServletRequest request,
HttpServletResponse response) {
doPost(request, response);
}
14
A Hello World servlet
(fromtheTomcat installation documentation)
public class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String docType =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">\n";
out.println(docType +
"<HTML>\n" +
"<HEAD><TITLE>Hello</TITLE></HEAD>\n" +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1>Hello World</H1>\n" +
"</BODY></HTML>");
}
}
15
The superclass
public class HelloServlet extends HttpServlet {
Every class must extend GenericServlet or a
subclass of GenericServlet
GenericServletisprotocol independent, so youcould
writeaservletto processany protocol
Inpractice, youalmostalwayswant to respondto an
HTTP request, so youextend HttpServlet
A subclass of HttpServlet must overrideat least
onemethod, usually onedoGet, doPost, doPut,
doDelete, init and destroy, or getServletInfo
16
The doGet method
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
Thismethod servicesaGET request
Themethod usesrequest to get theinformationthat wassent to
it
Themethod doesnot returnavalue; instead, itusesresponseto
get anI/O stream, andoutputs itsresponse
Sincethemethod doesI/O, itcanthrow anIOException
Any other typeof exceptionshouldbeencapsulatedasa
ServletException
ThedoPost method worksexactly thesameway
17
Parameters to doGet
Input is fromtheHttpServletRequest parameter
Our firstexampledoesntget anyinput, so well discussthisa
bitlater
Output is viatheHttpServletResponse object, which we
havenamed response
I/O inJ avaisveryflexiblebut also quitecomplex, so this
objectactsasanassistant
18
Using the HttpServletResponse
Thesecondparameter to doGet (or doPost) is
HttpServletResponse response
Everythingsent viatheWebhasaMIME type
Thefirstthingwemust do withresponse issettheMIME type of
our reply: response.setContentType("text/html");
This tells the client to interpret the page as HTML
Becausewewill beoutputting character data, weneeda
PrintWriter, handilyprovidedfor us bythegetWriter method
of response:
PrintWriter out = response.getWriter();
Now werereadyto createtheactual pageto bereturned
3
19
Using the PrintWriter
Fromhereon, itsjustamatter of usingour PrintWriter,
namedout, to producetheWebpage
Firstwecreateaheader string:
String docType =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">\n";
This line is technically required by the HTML spec
Browsers mostly dont care, but HTML validators do care
Thenusetheprintln methodof out oneor moretimes
out.println(docType +
"<HTML>\n" +
"<HEAD> ... </BODY></HTML>");
Andweredone!
20
Input to a servlet
A GET request supplies parameters in theform
URL ? name=value & name=value & name=value
(Illegal spacesaddedto makeitmorelegible)
Actual spacesintheparameter valuesareencodedby + signs
Other special charactersareencodedinhex; for example, an
ampersandisrepresentedby%26
Parameter names can occur morethan once, with
different values
A POST request supplies parameters in thesamesyntax,
only it is in thebody section of therequest and is
thereforeharder for theuser to see
21
Getting the parameters
Input parametersareretrievedviamessagesto the
HttpServletRequest objectrequest
Most of the interesting methods areinherited fromthe superinterface
ServletRequest
public Enumeration getParameterNames()
Returns anEnumeration of the parameter names
If no parameters, returns anempty Enumeration
public String getParameter(String name)
Returns the value of the parameter name as aString
If the parameter doesnt exist, returns null
If name has multiple values, only the first is returned
public String[] getParameterValues(name)
Returns anarray of values of the parameter name
If the parameter doesnt exist, returns null
22
Example of input parameters
public void doGet(HttpServletRequest request,
HttpServletResponse response) {
... stuff omitted ...
out.println("<H1>Hello");
String names[] =
request.getParameterValues("name");
if (names != null)
for (int i = 0; i < names.length; i++)
out.println(" " + names[i]);
out.println("!");
}

Você também pode gostar