Академический Документы
Профессиональный Документы
Культура Документы
Main Process
Request for CGI 1 Child Process for CGI 1
• Portability
• Power
• Efficiency and Endurance
• Safety
• Elegance
• Integration
• Extensibility and Flexibility
The Servlet Life Cycle
• A web server
communicates with
a Servlet through a
simple interface,
javax.servlet.Servlet
. This interface
consists of three
main methods:
• init()
• service()
• destroy()
and two ancillary
methods:
• getServletConfig()
• getServletInfo()
Servlet Life Cycle (contd)
Main Process
Request for Servlet1 Thread JVM
Servlet1
Servlet1
Request for Servlet2 Thread
Thread Servlet2
Servlet2
Request
Servletforinitialized
Servlet1 once; reused until destroyed and
garbage collected.
Java Servlet-based Web Server
Servlet Life Cycle (contd)
Life Cycle Of A Servlet (contd)
• A servlet is constructed and initialized. It then services zero
or more requests until the service that it extends shuts down
• Initialized only once, stays resident in memory while
servicing requests
• Multiple threads of execute service(), one for each client
connection
• The servlet interface defines the life cycle methods :
init()
service()
destroy()
init() Method
– javax.servlet.http
– javax.servlet
Servlet Interface (contd)
GenericServlet Class
Server GenericServlet subclass
request service()
service()
response
init service
Generic Servlet
destroy
extends
doGet(...) doOptions(…)
doPost(...) doDelete(…)
HttpServlet
doPut(…) doTrace(…)
What does the Server Receive
Searching
Found www.mcp.com
for www.mcp.com
server
client
http://www.mcp.com/index.html
Exception
Exception ServletException
ServletException UnavailableException
UnavailableException
KEY Class
Class ABSTRACT
ABSTRACTCLASS
CLASS Interface
Interface extends implements
Servlet
Servlet
GenericServlet ServletConfi
ServletConfi
javax.servlet.* GenericServlet
gg
service(req, res) Serializabl
Serializabl
ee
ServletReques
ServletReques ServletRespons
ServletRespons
tt ee
ServletInputStream
ServletInputStream ServletOutputStream
ServletOutputStream
Class
Class ABSTRACT
ABSTRACTCLASS
CLASS Interface
Interface implements
ServletContext / ServletConfig
• ServletConfig
– used to get initialization parameters
• getServletContext()
• String getInitParameter(String)
• Enumeration getInitParameterNames()
• ServletContext
– useful for logging & finding out about the
other servlets
• Servlet getServlet(String)
• Enumeration getServlets()
• Enumeration getServletNames()
• void log(String)
• void log(Exception, String)
GenericSer
GenericSer Serializabl
Serializabl
vlet
vlet ee
javax.servlet.http.* HTTPServlet
HTTPServlet
Class
Class ABSTRACT
ABSTRACTCLASS
CLASS Interface
Interface extends implements
Servlet Architecture
Methods for
Servlet managing a servlet and
communicating with
clients
HTTPServlet
ServletRequest
GET request
Servlet
Servlet
response
ServletResponse
Encapsulates communication
from server to client
package codecamp; A Simple Code Example
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
Public class ServletGet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse
response) throws ServletException,
IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<title>First
Servlet</title>");
out.println("<big>Hello Code Camp!
</big>");
}
}
Example
Write the following html file: mydisplay.html
<HTML> <HEAD>
<TITLE> calling servlets </TITLE> </HEAD>
<BODY>
<form method=get
action="http://localhost:8080/servlet/servletGet">
<input type=submit value="call servletGet">
</form>
</BODY> </HTML>
Click on the button “call servletGet” and note that the
earlier servlet is called.
GET /servlet/servletGet
/mydisplay.html HTTP/1.0
HTTP/1.0
http://localhost…/…/mydisplay.html
call servletGet
Example
Modify only the following line in html file:
mydisplay.html
<form method=post
action="http://localhost:8080/servlet/servletGet">
Click on the button “call servletGet” and note what
happens.
Write a html with three text fields for name, id and location,
with a submit button. Set the form method as ‘GET’, and
action as ‘servlet/servletGetParam’
Eg: servlet_get_HTML.html
Write a servlet with doGet() method. In the doGet() method
read the parameters and then send it back to the browser for
display
Eg: servletGetParam.java
Example
Write a html with three text fields for name, id and location,
with a submit button. Set the form method as ‘POST’, and
action as ‘servlet/servletGetParam’
Eg: servlet_post_HTML.html
Write a servlet with doPost() method. In the doPost() method
read the parameters and then send it back to the browser for
display
Eg: servletPost.java
Interface ServletRequest
– information about the client
• name of the host and the IP address of client
• parameters sent from the client browser
• scheme used by the browser to communicate
to servlet (eg. http; https; ftp;…..)
• protocol used by client (eg. ftp)
• access to the ServletInputStream (which
allows servlet to read binary data from the
client )
– information about server
• name of the server
• port used by the server
ServletRequest…
Eg: helloservletGet.java
ServletResponse Interface
Eg : ServletGet.java
Status Codes
Mnemonic constant Code Displayed Message
SC_OK 200 OK
SC_NO_CONTENT 204 No Content
SC_MOVED_PERMANENTLY 301 Moved Permanently
SC_MOVED_TEMPORARILY 302 Moved Temporarily
SC_NOT_FOUND 404 Not Found
SC_INTERNAL_SERVER_ERROR 500 Internal Server error
SC_NOT_IMPLEMENTED 501 Not Implemented
SC_SERVICE_NOT_AVAILABLE 503 Service Not Available
SC_BAD_GATEWAY 502 Invalid response
Redirecting a Request
Eg: MyCounterServ.java
Eg: MyCounterServSyn.java
Example
Write a servlet that informs the client that the site has moved,
and allow let the browser go to the new url automatically
after 9 seconds.
Eg: RelocateServlet.java
Request Dispatcher
getServletContext().getRequestDispatcher("
/welcome.jsp");
rd.include(request, response);
Sending Multimedia Content
Eg: servletImage.java
Problem: If we write 2 images to the
application, it will read only the first one.
Hence, one can send only one image at a
time.
Example
Eg: servletImageHTML.java
Note: All the
Solution: senddata
the to
html
be sent
tag <img
is stored
src=“…”>,
in a and the
browser will open connection
byteArrayOutputStream and and
sent get
all at
theonce.
information
This is
from server.
buffering butThis
could
wayslow
any
down
number
whenoflotimages
of information
can be is
passed.
being sent to the client.
User Authentication
Eg: secureServlet.java
Session Tracking
Eg: SessionDemo.java
Ways of Session-Tracking
• Inter-Servlet Communication
How to call a method of another Servlet
Servlet Environment (contd)