What is a Servlet?
• Servlets are Java programs that can be run
dynamically from a Web Server
• Servlets are a server-side technology
• A Servlet is an intermediating layer between
an HTTP request of a client and the Web
server
A Java Servlet
request request
Servlet
response response
Web
browser
Web server
Tools you need
• Java Development Kit (JDK)
• Java Servlet Development Kit (JSDK)
– include packages:
javax.servlet
javax.servlet.http
– available from
http://java.sun.com/products/servlet
• Servlet Engine
Servlet Hierarchy
service(ServletRequest,
Servlet ServletResponse)
Generic Servlet
doGet(HttpServletRequest ,
HttpServletResponse)
HttpServlet doPost(HttpServletRequest
HttpServletResponse)
doPut
YourOwnServlet
doTrace
…
Servlet Life Cycle
• When the Servlet in instantiated, its
method init() is begin invoked
– External parameters are supplied
• Upon a request, its method service() is
being invoked
• Before the Servlet removal, its method
destroy() is being invoked
Servlet Life Cycle
Garbage
Servlet Class Collection
A GenericServlet handling a request
request
service( )
response
Check:
http://java.sun.com/products/servlet/2.2/javadoc/
servletconfig
A servlet configuration object used by a
servlet container used to pass information
to a servlet during initialization.
Servlet.getServletConfig(
• Defines a set of methods that a servlet
uses to communicate with its servlet
container
public ServletContext getServletContext()
Initializing Servlets
• The method init has a parameter of type
ServletConfig
• ServletConfig has methods to get
external initialization parameters
– In Tomcat, these parameters are set in
web.xml
• To make initializations, override init()
and not init(ServletConfig)
– init() is automatically called by after
performing default initializations
An HTTP servlet handling
GET and POST request
Server HttpServlet subclass
Get request
response doGet( )
response doPost( )
Main Process
Request for JVM Init()
Servlet 1 Thread
service() Servlet1
Request for Thread
Servlet 2
Thread Servlet2
Request for
Servlet 1
Example: HelloWorldServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;