BB: Servlets Java ATS Application Programming

:
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  Finalizing a ServletAccenture All Rights Reserved. © 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. 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 Rights Reserved. to ©2004 Accenture All developed

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 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. 8

© Accenture 2005 All Rights Reserved

Technical Basics of Servlets
Servlet
Interface

Interfaces  Servlet HttpServletRequest HttpServletResponse

implements

 

GenericServlet

Class

Classes
extends

 

HttpServlet GenericServlet

HttpServlet

Class

©2004 Accenture All Rights Reserved.
© Accenture 2005 All Rights Reserved

9

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 javax.Servlet.http.HttpServlet class contains All Rights Reserved

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 init() destroy() unloading

requests

service()

responses

©2004 Accenture All Rights Reserved.
© Accenture 2005 All Rights Reserved

12

Initializing a Servlet

© Accenture 2005 All Rights Reserved

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 All Rights Reserved. 13 super.init(ServletConfig config).

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. }

14

© Accenture 2005 All Rights Reserved

Writing Service Methods

© Accenture 2005 All Rights Reserved

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 are called by the 15 doPut, and doTrace methods Reserved.

Maintaning Client State

© Accenture 2005 All Rights Reserved

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

Maintaining Client State

© Accenture 2005 All Rights Reserved

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

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 ©2004cookies. Rights Reserved. by off Accenture All You do this 18

Session Tracking

© 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 serverspecific 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. }

22

© Accenture 2005 All Rights Reserved

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>" + ©2004 Accenture All Rights Reserved. "</html>"); © 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 session.invalidate(); All Rights Reserved. © 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("<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.
© 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)
26

© Accenture 2005 All Rights Reserved

An easier way©2004 Accenture All Rights Reserved. class to do one is Extend the

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 27 ©2004 Accenture All Rights Reserved.

© Accenture 2005 All Rights Reserved

Questions & Comments

©2004 Accenture All Rights Reserved.
© Accenture 2005 All Rights Reserved

28