Servletsintroduction Life Cycle
Servletsintroduction Life Cycle
Designed By:
www.interviewDuniya.com
Prerequisites
For this section you are expected to
know Java programming including:
while and for loops (vital)
if (vital)
Passing parameters to methods (vital)
Arrays and Strings (important)
The Enumeration class (important)
Threads and synchronized (useful)
Exceptions try and catch (useful)
www.interviewDuniya.com
Serving Static HTML
Web servers where designed to provide
web browsers with HTML.
The HTML was read from text files by
the server and sent to the client using
HTTP. The web server does not modify
the HTML. This is now termed static
HTML serving
HTML doGet or doPost Server Machine
HTML
Client Web Web Page
Machine Server on disk
HTML
Web Browser
www.interviewDuniya.com
Static HTML the Problem
•Modern uses of web pages often require pages to be
dynamically generated.
•For example a chat system would display any new
messages each time you hit refresh. This requires
the web page the browser requests to be modified
each time someone adds a new message.
•Until recently there was no easy way to do this
because
• web browsers were not designed to rewrite web
pages
• web browsers are stateless so they process each
request in isolation without reference or memory
of what request came before it.
www.interviewDuniya.com
Why servlets over CGI
script?
A Servlet does not run in a separate process.
This removes the overhead of creating a new Perl 1
process for each request.
Browser 1
Browser 2 Web Perl 2
A Servlet stays in memory between requests. A Server
CGI program (and probably also an extensive Browser N
runtime system or interpreter) needs to be
loaded and started for each CGI request. Perl N
www.interviewDuniya.com
What can you build with Servlets?
Search Engines
Personalization Systems
E-Commerce Applications
Shopping Carts
Product Catalogs
Intranet Applications
Groupware Applications: bulletin boards, file
sharing, etc.
www.interviewDuniya.com
Servlets - a solution for
dynamically generating
HTML
Servlets are programs written in Java which run
on the web server and communicate using with
the web browser using HTTP and HTML
Servlets are compatible with all web browsers
because servlets communicate with the browser
using only HTML and HTTP
Servlets are simple to write because they are
written in standard Java
Most of the communication is done for you by
the Servlet class. No need to mess around with
Sockets, TCP/IP or Java serialisation.
www.interviewDuniya.com
What is a Servlet
Java technology for Common Gateway Interface
(CGI)
Servlets are Java programs that serve as an
intermediating layer between an HTTP request
of a client and applications in the Web server
www.interviewDuniya.com
A Servlet is a Java class that extends the web server's
service capabilities.
When the client sends a request to the server the.
Server can forward the request to a Servlet and let it
handle the request.
Servlets provide open, cross-server and OS APIs.
Servlets have a clean design; This leads to simplicity.
Servlets live inside a Servlet Container.
www.interviewDuniya.com
What Is a Servlet Container
Sometimes called a Servlet Engine.
The Servlet Container provides Servlets
with the environment, configuration
and runtime needed to support the
Servlet APIs:
Load the Servlets.
Initialize the Servlets.
Execute the Servlets.
Destroy the Servlets.
Sending a
request and
receiving a
response
www.interviewDuniya.com
Who Backs Servlets?
www.interviewDuniya.com
Function Cycle of a Servlet
5.) The created HTML page is then transmitted back to the user
6.) The requested information is displayed in the user’s web
browser
www.interviewDuniya.com
Servlet Life Cycle
Servlet is destroyed
www.interviewDuniya.com
The Basic Structure of an HttpServlet
www.interviewDuniya.com
void init(ServletConfig sc) throws ServletException;
www.interviewDuniya.com
The Servlet Lifecycle
www.interviewDuniya.com
The Servlet life-cycle defines:
How a Servlet is initialized.
How a Servlet is serving users and how many times.
www.interviewDuniya.com
In brief…the sequence of events..
The sequence of events starts with a browser sending a request
to a Web server.
The server hands the request to a Servlet Container.
The container loads the servlet (if it isn't already loaded),
instantiates a request and response objects, and then hands these
objects to the servlet by calling first its init() method, then its
service() method, and lastly the destroy() method.
The service() method will typically call one of the doXXX()
methods such as doGet().
www.interviewDuniya.com
Servlet Instantiation
The container instantiates a new Servlet in two
occasions:
A user request service from a Servlet that was not
instantiated yet.
The Servlet is in the list of startup Servlets and the
container is starting.
www.interviewDuniya.com
Servlet Initialization
After the instantiation, the container
initializes the Servlet.
The container casts the new instance to a
Servlet object and initializes it by calling an
init() method.
If
initialization fail the Servlet creation fail and
the new instance is garbage collected.
www.interviewDuniya.com
Init() …
A code for initialization that is called only once (e.g., creating
the tables of the database)
Initialization parameters are server specific
Many times these parameters are used to specify the
maximum or minimum number for your Servlet.
For example, if you have a banking account, there is typically
a minimum amount required to maintain the account. The
initial parameter could be set to this minimum number and
then your Servlet could access it to check the object's value
www.interviewDuniya.com
Service Phase
After the Servlet initialization, the container can ask the
Servlet to serve incoming requests.
The container will call the Servlet’s service() method.
A Servlet may handle many concurrent requests.
By different threads, all of them running in the same
service methods.
The service method should be thread safe.
Multithreading
By default the servlet need to be multithread safe!
www.interviewDuniya.com
singlethreadmodel
javax.servlet
www.interviewDuniya.com
Http Methods
when u click on Submit on your JSP page...you
will be directed to the method either
doGet() or doPost() in the servlet
www.interviewDuniya.com
HTTP Methods
POST:
Data sent in two steps
Designed for Posting information
Browser contacts server
Sends data
GET:
Contacts server and sends data in single step
Appends data to action URL separated by question mark
Designed to get information
The amount of query information is usually limited
to 1KB.
www.interviewDuniya.com
The main diff in these methods
When you select GET as method in your form the data you
pass from that JSP, will be appended to the URL with your
servlet address.......
where if you select POST then, any kind of data will not be
appended to the URL........it will be passed directly(but u
can not see appended data on the URL)
www.interviewDuniya.com
Other Methods
HEAD: Client sees only header of response to
determine size, etc…
PUT: Place documents directly on server
DELETE: Opposite of PUT
TRACE: Debugging aid returns to client
contents of its request
OPTIONS: what options available on server
www.interviewDuniya.com
HttpServlet Request Handling
www.interviewDuniya.com
Destroying Servlets
Destroying:
destroy() is a servlet life-cycle method called by
servlet container to kill the instance of the servlet.
destroy() method
make sure all service threads complete
www.interviewDuniya.com
End of servlet life cycle
www.interviewDuniya.com
Servlet Architecture
www.interviewDuniya.com
Working with Servlets
www.interviewDuniya.com
Servlet Package
javax.servlet
The Servlet interface defines methods that
manage servlets and their communication with
clients
Client Interaction: when it accepts call, receives
two objects that implements
ServletRequest
ServletResponse
www.interviewDuniya.com
Architecture
Servlet
Generic Servlet
HttpServlet
YourOwnServlet
www.interviewDuniya.com
Generic Servlet & HTTP Servlet
GenericServlet
Client
request
Server service ( )
response
HTTPServlet
Browser
request doGet( )
HTTP service ( )
Server
response doPost( )
www.interviewDuniya.com
Difference between GenericServlet
and HttpServlet
GenericServlet is for servlets that might not use
HTTP, like for instance FTP servlets.(future
growth specs)
GenericServlet is protocol independent, whereas
HttpServlet is protocol dependent
In GenericServlets you cannot use Cookies or
HttpSession.
www.interviewDuniya.com
Session tracking is not possible, redirection is not
possible.
Http servlets overrides doGet and doPost methods.
Generic servlet overides service method.
generic servlet is superclass for HttpServlet.
httpservlet class can also have service() method.it's not
necessary that you can only have doGet() and doPost()
method defined.
Generic servlet is used for small data transfer whereas
HttpServlet is used for huge data transfer.
www.interviewDuniya.com
Writing a Servlet
Your servlets will usually extend the HttpServlet
class. Which provides default implementations of
init, you only need to override this if you want to
do some initialisation such as open a database
connection.
destroy, you only need to override this if you
want to do some cleaning up such as closing a
database connection.
service, should not normally be overridden
because it decides which of the doX methods
should be called
www.interviewDuniya.com
Writing a Servlet..
doGet. HTTP Get is the default way a web
browser makes a request and this causes the
doGet method of the servlet to be invoked so
you would normally override this method
doPost. If you don't respond to a Post you
don't need to override this method.
www.interviewDuniya.com
HTTP Get or Post?
•The main differences between Get and Post are
www.interviewDuniya.com
Servlet doGet and doPost
doGet and doPost have identical signatures and
receive two parameters from the service method..
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws IOException,
ServletException
www.interviewDuniya.com
• HttpServletRequest is an Object containing information
about the request from the web browser.
Such as the login name of the user and any values in the header field sent
by the web browser.
Any parameters sent as part of the request
Any initialisation parameters set in the deployment descriptor
It also supplies any session and cookies (more on these later)
www.interviewDuniya.com
Client-Server Interaction
HTTP Request (Sending request message to
Server ):
www.interviewDuniya.com
HTTP Response (Sending response message to client):
• The response sent by the server also consists of three parts:
• response line (server protocol and status code)
• header variables (server and response information)
• message body (response, such as HTML)
www.interviewDuniya.com
Servlet Output
Request contains Response allows
any parameters, you to add cookies
Cookies and and send data to
Sessions send by the client
the client
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{ The servlet must get the
response.setContentType("text/html"); communications channel from the
PrintWriter out = response.getWriter(); response Object and set the
encoding before sending anything to
the client
out.println("<HTML>");
out.println("<HEAD><TITLE>First Servlet
program</TITLE></HEAD>");
out.println("<BODY>");
out.println("<H1>Welcome to Servlets</H1>");
out.println("</BODY>");
out.println("</HTML>"); <HTML>
<HEAD><TITLE>First Servlet Program</TITLE></HEAD>
out.close(); <BODY>
} <H1>Welcome to Servlets</H1>
</BODY>
www.interviewDuniya.com
</HTML>
First Servlet Example
Servlets are not part of the
standard SDK, they are part of
the J2EE
import java.io.*;
import javax.servlet.*; Servlets normally extend
import javax.servlet.http.*; HttpServlet
// initialise servlet
ServletConfig config = servlet.getServletConfig();
servlet.init(config);
www.interviewDuniya.com
Compiling
www.interviewDuniya.com
Calling the Servlet
Calling the servlet is done from the Web
browser:
http://host:port/servlet/ServletName
www.interviewDuniya.com
Calling the Servlet
www.interviewDuniya.com
Packages
Add packege packageName to the java code to
create a package
Put the classes files under
tomcat_home/webapps/ROOT/WEB-
INF/classes/packageName
Call the servlet with
http://host:port/servlet/packageName.servletNa
me
www.interviewDuniya.com
The Servlet API
www.interviewDuniya.com
What’s in the APIs
The Servlet APIs defines:
A servlet lifecycle – how a servlet is created, used
and destroyed.
A programmer interface – how a servlet looks like
to the container and how the container looks like to
the servlet.
www.interviewDuniya.com
A Destroy Example
public void destroy() {
www.interviewDuniya.com
Servlet Destruction
A container may destroy the Servlet because:
It wants to preserve resources (this is not common).
The container is shutting down.
Note that this means that a certain Servlet will usually stay
“alive” for a very long time and is going to serve many users.
www.interviewDuniya.com
Supporting Servlets
The Web server must support servlets:
Apache Tomcat
Sun’s JavaServer Web Development Kit (JSWDK)
…
www.interviewDuniya.com
“Listening” to a Shutdown
www.interviewDuniya.com
Passing Multiple Parameters to Servlets
Enumeration p=request.getParameterNames();
while (p.hasMoreElements())
{
String n=(String)p.nextElement();
String v=request.getParameter(n);
out.println("parameter name is "+n+" parameter value" +v+"<br>");
}
www.interviewDuniya.com
Using forms to Pass Parameters
www.interviewDuniya.com
Using Choice boxes
The code is a little more complex than a TEXT field.
<FORM METHOD="POST"
ACTION="http://localhost:8080/servlet/cw?action=submit">
<br><br>question 0 what grade do you want on this coursework?
<br> F
<input type="radio" name="q0" value=0 > All the choices associated
<br> resit with the same choice box
<input type="radio" name="q0" value=1 > have the same name!
<br> fail
<input type="radio" name="q0" value=2 > Each possible choice should
<br> retake have a different value.
<input type="radio" name="q0" value=3 >
<INPUT TYPE="SUBMIT" VALUE="Mark">
</form>
When the submit button is
pressed the parameter q0 will
have the value 0 or 1 or 2 or 3
www.interviewDuniya.com
Using Choice boxes
You may have one than one independent choice
box in the same form. The result of each select is
passed as separate parameters.
www.interviewDuniya.com
Using Choice boxes
In this case one choice is called q0 and the second q1
<FORM METHOD="POST"
ACTION="http://www3.unl.ac.uk:8186/kingj1/servlet/cw?action=submit">
<br><br>question 0 what grade do you want on this coursework?
<br> F
<input type="radio" name="q0" value=0 >
<br> resit
<input type="radio" name="q0" value=1 >
<br><br>question 0 what grade do you want on the exam?
<br> F
<input type="radio" name="q1" value=0 >
<br> resit
<input type="radio" name="q1" value=1 >
<INPUT TYPE="SUBMIT" VALUE="Mark">
</form>
www.interviewDuniya.com
Thread Unsafe
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class multi extends HttpServlet {
int count=0;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<HEAD><TITLE> Thread UNSAFE example </TITLE>
</HEAD> ");
out.println("<BODY>");
out.println("<H1> old count is "+count+"</H1>");
count=count+1; Read then
try { Thread.sleep(4000); } catch (Exception e) { } modify then
out.println("<H1> new count is "+count+"</H1>"); write
out.println("</BODY>");
out.println("</HTML>");
}
}
www.interviewDuniya.com
Thread Safe
A good way to make sure servlets are thread safe is to have no
global data. But this is not always practical.
A partial solution is to store data on a per client basis. But this
requires sessions or cookies. It does not work if one client
machine has two instances of the web browser accessing the
servlet concurrently
The best method is to mark the sections of code that access
global data as synchronized. This allows the sections that do
not access global data to run concurrently
www.interviewDuniya.com
Thread Safe
Enclose sections that use global data in synchronized sections
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class multi extends HttpServlet {
int count=0;
Object s=new Object();
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<HEAD><TITLE> Thread UNSAFE example </TITLE> </HEAD> ");
out.println("<BODY>");
synchronized (s) {
out.println("<H1> old count is "+count+"</H1>"); Can not be
count=count+1; executed
try { Thread.sleep(4000); } catch (Exception e) { } concurrently
out.println("<H1> new count is "+count+"</H1>"); }
out.println("</BODY>");
out.println("</HTML>");
}
www.interviewDuniya.com
}
Servlets vs. JSP
• JSPs
– Look like standard HTML or XHTML
• Normally include HTML or XHTML markup
– Known as fixed-template data
– HTML codes can be written easily
– Used when content is mostly fixed-template data
• Small amounts of content generated dynamically
• Servlets
– HTML codes have to be written to the PrintWriter or
OutputStream
– Used when small amount of content is fixed-template data
• Most content generated dynamically
www.interviewDuniya.com
Summary
The servlet life cycle?
www.interviewDuniya.com
End of Servlets Basics
and
Servlets Life Cycle
www.interviewDuniya.com