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 ©2004 Accenture All Rights Reserved. Finalizing a Servlet © Accenture 2005 All Rights Reserved
2
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.
© Accenture 2005 All Rights Reserved
3
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.
© Accenture 2005 All Rights Reserved
4
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 to ©2004 Accenture All Rights Reserved.
© Accenture 2005 All Rights Reserved
5
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.
© Accenture 2005 All Rights Reserved
6
Servlet Implementation
Servlets must implement the javax.Servlet.Servlet interface. Both javax.Servlet.GenericServlet and javax.Servlet.http.HttpServlet (for HTTPspecific requests) classes are implementations of the Servlet interface.
©2004 Accenture All Rights Reserved. © Accenture 2005 All Rights Reserved
7
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.
© Accenture 2005 All Rights Reserved
8
Technical Basics of Servlets Servlet
Interface
implements
GenericServlet
Interfaces
Servlet
HttpServletRequest
HttpServletResponse
Class
Classes extends
HttpServlet
HttpServlet
GenericServlet
Class
©2004 Accenture All Rights Reserved. © Accenture 2005 All Rights Reserved
9
Servlet Life Cycle 1.
Loading, Instantiation and Initialization
2.
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.
Operational
The container invokes the Servlet’s service method, passing request and response objects. ©2004 Accenture All Rights Reserved. 10 © Accenture2005 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. © Accenture 2005 All Rights Reserved
11
Servlet Life Cycle loading destroy()
init()
unloading
requests
service()
responses
©2004 Accenture All Rights Reserved. © Accenture 2005 All Rights Reserved
12
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 ©2004 Accenture config) All Rights Reserved. 13 super.init(ServletConfig .
© Accenture 2005 All Rights Reserved
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, ©2004 Accenture All Rights Reserved. doPut, and doTrace methods are called by the15
© Accenture 2005 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, ©2004 Accenture All Rights Reserved. you use the session's invalidate method to 17
© Accenture 2005 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 YouReserved. do this by Accenture All. Rights 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.
© Accenture 2005 All Rights Reserved
19
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 serverspecific grace period has elapsed, whichever comes first. ©2004 Accenture All Rights Reserved.
© Accenture 2005 All Rights Reserved
20
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.
© Accenture 2005 All Rights Reserved
21
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("" + "" + "" + "
Servlet Example 1" + "" + "" + "Hello " + name + "! |
" + "" + ©2004 Accenture All Rights Reserved. ""); © Accenture}2005 All Rights Reserved
23
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. session.invalidate(); © Accenture 2005 All Rights Reserved
24
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(""); out.println(" Simple Servlet "); out.println(""); out.println("Hello World!!!
"); out.println(""); out.close(); ©2004 Accenture All Rights Reserved.
© Accenture 2005 All Rights Reserved
25
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)
Accenture All Rights Reserved. An easier way©2004 to do one is Extend the class
© 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/CourseMaterials/pdf/csajsp2/02-Servlet-Basics.pdf ©2004 Accenture All Rights Reserved. 27
© Accenture 2005 All Rights Reserved
Questions & Comments
©2004 Accenture All Rights Reserved. © Accenture 2005 All Rights Reserved
28