Sei sulla pagina 1di 28

BB: Servlets

ATS Application Programming: Java


Programming

© Accenture 2005 All Rights Reserved Course Code #Z16325


Objectives
This review session will cover Servlets.
Included in this review are:
 Background
 What is a Servlet?

 Servlet Life Cycle

 Initializing a Servlet

 Writing Service Methods

 Maintaining Client State

 Session Tracking

 Finalizing a Servlet ©2004 Accenture All Rights Reserved. 2


© Accenture 2005 All Rights Reserved
Overview
Detailed in this review:

 A brief introduction of Servlets


 Definition of what is a Servlet
 Discussion of a Servlet’s life cycle
 Explanation of how a Servlet maintains
client state and does session tracking

©2004 Accenture All Rights Reserved. 3


© Accenture 2005 All Rights Reserved
Overview
 The use of the server platform was
investigated and led to the development of
Common Gateway Interface (CGI).

 CGI gained immense popularity, but it had


shortcomings including platform dependence
and lack of scalability.

 This meant that a better solution was needed.


©2004 Accenture All Rights Reserved. 4
© Accenture 2005 All Rights Reserved
Overview
 Sun Microsystems developed the Java Servlet
Technology to replace CGI.

 Servlets are portable, scalable, robust and


powerful.

 Hypertext Preprocessor (PHP) and


Microsoft’s Active Server Pages (ASP) are
other similar technologies developed
©2004 Accenture All Rights Reserved. to 5
© Accenture 2005 All Rights Reserved
What is a Servlet?
 A Servlet is a Java class that is used to extend
the access capabilities of servers that host
applications via a request-response
programming model.

 Servlets can respond to any type of request,


but its more common use is to extend the
applications hosted by web servers.
©2004 Accenture All Rights Reserved. 6
© Accenture 2005 All Rights Reserved
Servlet Implementation
 Servlets must implement the
javax.Servlet.Servlet interface. Both
javax.Servlet.GenericServlet and
javax.Servlet.http.HttpServlet (for HTTP-
specific requests) classes are implementations
of the Servlet interface.

©2004 Accenture All Rights Reserved. 7


© Accenture 2005 All Rights Reserved
Servlet Implementation
 The interfaces javax.Servlet.ServletRequest
and ServletResponse define the objects that
provide client request and application response
information to a Servlet. The interfaces
javax.Servlet.http.HttpServletRequest and
HttpServletResponse extend their generic
counterparts to provide request and response
information for HTTP Servlets.

©2004 Accenture All Rights Reserved. 8


© Accenture 2005 All Rights Reserved
Technical Basics of Servlets
Servlet Interface
Interfaces
 Servlet

implements  HttpServletRequest
 HttpServletResponse

GenericServlet Class

Classes

extends  HttpServlet
 GenericServlet

HttpServlet Class

©2004 Accenture All Rights Reserved. 9


© Accenture 2005 All Rights Reserved
Servlet Life Cycle
1. Loading, Instantiation and Initialization
 The Servlet is loaded into the Servlet
Container/Web Server.
 An instance of the Servlet class is created.
 The container calls the Servlet’s init method. The
init method is usually overridden to acquire
resources.
2. Operational
 The container invokes the Servlet’s service method,
passing request and response objects.
©2004 Accenture All Rights Reserved. 10
© Accenture2005 The
All Rightsjavax.Servlet.http.HttpServlet
Reserved class contains
Servlet Life Cycle
1. Finalization
 The container calls the Servlet’s destroy
method. Overriding this method releases the
resources acquired by the Servlet.

©2004 Accenture All Rights Reserved. 11


© Accenture 2005 All Rights Reserved
Servlet Life Cycle

loading

init() destroy()

unloading

requests service() responses

©2004 Accenture All Rights Reserved. 12


© Accenture 2005 All Rights Reserved
Initializing a Servlet
 The container calls the init method of the
Servlet once to initialize it. A ServletException
is thrown if initialization fails.
 Fortunately, we no longer have to implement
this method since the GenericServlet class
already has one. In cases where customization
is absolutely necessary, GenericServlet also
has an overloaded init method to further
simplify the process – no need to call
super.init(ServletConfig
©2004 Accenture config)
© Accenture 2005 All Rights Reserved
.
All Rights Reserved. 13
Initializing a Servlet
 The following example overrides the
overloaded init method:

public class Hello extends HttpServlet {


public void init() {
System.out.println(“Initializing
Servlet…");
}
} ©2004 Accenture All Rights Reserved.
© Accenture 2005 All Rights Reserved
14
Writing Service Methods
 The service provided by a Servlet is
implemented in the service method of a
GenericServlet, in the doMethod methods
(where Method can take the value Get, Delete,
Options, Post, Put, or Trace) of an HttpServlet
object or in any other protocol-specific
methods defined by a class that implements the
Servlet interface.
 The doGet, doDelete, doOptions, doPost,
doPut, and doTrace methods
©2004 Accenture
© Accenture 2005 All Rights Reserved
are called by the15
All Rights Reserved.
Maintaning Client State
 Web-based applications are responsible for
maintaining state, called a session, in order to
associate a series of HTTP requests from a
client.
 Java Servlet technology provides an API for
managing sessions and allows several
mechanisms for implementing sessions.
 Sessions are represented by an
javax.Servlet.HttpSession object.
©2004 Accenture All Rights Reserved. 16
 The getSession method of request objects is
© Accenture 2005 All Rights Reserved
Maintaining Client State
 Because there is no way for an HTTP client to
signal it no longer needs a session, each
session has an associated timeout so that its
resources can be reclaimed. The timeout
period can be accessed by using a session's
[get|set]MaxInactiveInterval method. You
can also set the timeout period using the
deploy tool.
 When a particular client interaction is finished,
you use the session's invalidate
©2004 Accenture
© Accenture 2005 All Rights Reserved
method to 17
All Rights Reserved.
Session Tracking
 A web container can use several methods to
associate a session with a user, all of which
involve passing an identifier between the client
and the server. The identifier can be maintained
on the client as a cookie
(javax.Servlet.http.Cookie), or the web
component can include the identifier in every
URL that is returned to the client.
 If your application uses session objects, you
must ensure that session tracking is enabled by
having the application rewrite URLs whenever
the client turns ©2004
off cookies
Accenture All. Rights
YouReserved.
do this by 18
© Accenture 2005 All Rights Reserved
Finalizing a Servlet
 The container calls the destroy
method of the Servlet to:
– Finalize it
– Release any resources the Servlet is
using
– Save any persistent state

©2004 Accenture All Rights Reserved. 19


© Accenture 2005 All Rights Reserved
Finalizing a Servlet
 The server tries to ensure that all of a
Servlet's service methods are
complete by calling the destroy
method only after all service requests
have returned or after a server-
specific grace period has elapsed,
whichever comes first.
©2004 Accenture All Rights Reserved. 20
© Accenture 2005 All Rights Reserved
Finalizing a Servlet
 Like the init method, the
GenericServlet class also has an
implementation for the destroy
method. The developer must make
sure that all resources taken up in the
initialization can be released in
calling this method.
©2004 Accenture All Rights Reserved. 21
© Accenture 2005 All Rights Reserved
Finalizing a Servlet
The following example overrides the destroy
method:

public class Hello extends HttpServlet {


public void destroy() {
System.out.println(“Finalizing
Servlet..");
}
} ©2004 Accenture All Rights Reserved.
© Accenture 2005 All Rights Reserved
22
Example: A Simple Servlet Class
import java.io.*; import javax.Servlet.*;
import javax.Servlet.http.*;
public class Hello extends HttpServlet {
// the doPost method is one of the service methods of HttpServlet
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// retrieves the client’s name
String name = request.getParameter("your_name");
// displays greeting
response.setContentType("text/html");
PrintWriter out = response.getWriter();

out.print("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2//EN\">" +


"<html>" +
"<head>" +
"<title>Servlet Example 1</title>" +
"</head>" +
"<body>" +
"<tr><td>Hello " + name + "!</td></tr>" +
"</body>" +
"</html>"); ©2004 Accenture All Rights Reserved. 23
© Accenture}2005 All Rights Reserved
Example: Maintaining Session
public class SessionExample extends HttpServlet {
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

// Get the user's session and shopping cart


HttpSession session = request.getSession();
...
// Invalidate the session
©2004 Accenture All Rights Reserved. 24
session.invalidate();
© Accenture 2005 All Rights Reserved
Another Servlet Example
Import java.io.*;
import javax.Servlet.*;
import javax.Servlet.http.*;

public class HelloWorldServlet extends HttpServlet {

public void init() throws ServletException {


// Initialize and run when loaded. Can use default.
}
public void destroy() {
// Release resources, exit, etc. Can use default.
}
public void doGet(HttpServletRequest req, HttpServletResponse rsp)
throws ServletException, IOException
{
rsp.setContentType("text/html");

PrintWriter out = rsp.getWriter();


out.println("<html>");
out.println("<head><title> Simple Servlet </title></head>");
out.println("<body>");
out.println("<h1>Hello World!!!</h1>");
out.println("</body></html>");
out.close();
}
}
©2004 Accenture All Rights Reserved. 25
© Accenture 2005 All Rights Reserved
Summary
 A Servlet is a class that responds to a service
request.
 It implements the javax.Servlet.Servlet
interface:
– init called once to initialize the Servlet
– service called to get the Servlet to respond to a
client request.
– destroy called at termination (close / deallocate
resources)
 An easier way©2004
to do one is Extend the class
Accenture All Rights Reserved.
© Accenture 2005 All Rights Reserved
26
Resources
Helpful Websites:
 http://java.sun.com/j2ee/1.4/docs/ tutorial/doc/J2EE

 http://java.sun.com/j2ee/1.4/docs/api/
index.html
 http://faculty.washington.edu/hanks/Courses/460/w
 http://www.cs.niu.edu/~jzhou/courses/csci470/Serv
 http://courses.coreServlets.com/Course-
Materials/pdf/csajsp2/02-Servlet-Basics.pdf
©2004 Accenture All Rights Reserved. 27
© Accenture 2005 All Rights Reserved
Questions & Comments

©2004 Accenture All Rights Reserved. 28


© Accenture 2005 All Rights Reserved

Potrebbero piacerti anche