servlet

28
© Accenture 2005 All Rights Reserved Course Code #Z16325 ATS Application Programming: ATS Application Programming: Java Programming Java Programming BB: Servlets BB: Servlets

Upload: mohanraop

Post on 15-Nov-2014

382 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Servlet

© Accenture 2005 All Rights Reserved Course Code #Z16325

ATS Application Programming: Java ATS Application Programming: Java ProgrammingProgramming

BB: ServletsBB: Servlets

Page 2: Servlet

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

22

© Accenture 2005 All Rights Reserved

ObjectivesObjectivesThis review session will cover Servlets.This review session will cover Servlets.

Included in this review are:Included in this review are: BackgroundBackground What is a Servlet?What is a Servlet? Servlet Life CycleServlet Life Cycle Initializing a ServletInitializing a Servlet Writing Service MethodsWriting Service Methods Maintaining Client StateMaintaining Client State Session TrackingSession Tracking Finalizing a ServletFinalizing a Servlet ResourcesResources Q & AQ & A

Page 3: Servlet

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

33

© Accenture 2005 All Rights Reserved

OverviewOverview

Detailed in this review:Detailed in this review:

A brief introduction of ServletsA brief introduction of Servlets Definition of what is a ServletDefinition of what is a Servlet Discussion of a Servlet’s life cycleDiscussion of a Servlet’s life cycle Explanation of how a Servlet maintains Explanation of how a Servlet maintains

client state and does session trackingclient state and does session tracking

Page 4: Servlet

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

44

© Accenture 2005 All Rights Reserved

OverviewOverview

The use of the The use of the server platformserver platform was investigated was investigated and led to the development of and led to the development of Common Common Gateway Interface (CGI)Gateway Interface (CGI)..

CGI gained immense popularity, but it had CGI gained immense popularity, but it had shortcomings including shortcomings including platform dependenceplatform dependence and and lack of scalability.lack of scalability.

This meant that a better solution was needed.This meant that a better solution was needed.

Page 5: Servlet

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

55

© Accenture 2005 All Rights Reserved

OverviewOverview

Sun MicrosystemsSun Microsystems developed the developed the Java Servlet Java Servlet TechnologyTechnology to replace CGI. to replace CGI.

Servlets are Servlets are portableportable, , scalablescalable, , robustrobust and and powerfulpowerful. .

Hypertext Preprocessor (PHP)Hypertext Preprocessor (PHP) and and Microsoft’sMicrosoft’s Active Server Pages (ASP)Active Server Pages (ASP) are other similar are other similar technologies developed to replace CGI.technologies developed to replace CGI.

Page 6: Servlet

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

66

© Accenture 2005 All Rights Reserved

What is a Servlet?What is a Servlet?

A Servlet is a Java class that is used to extend A Servlet is a Java class that is used to extend the access capabilities of servers that host the access capabilities of servers that host applications via a applications via a request-response request-response programming modelprogramming model..

Servlets can respond to any type of request, Servlets can respond to any type of request, but its more common use is to extend the but its more common use is to extend the applications hosted by web servers.applications hosted by web servers.

Page 7: Servlet

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

77

© Accenture 2005 All Rights Reserved

Servlet ImplementationServlet Implementation

Servlets Servlets mustmust implement the implement the javax.Servlet.Servletjavax.Servlet.Servlet interface. Both interface. Both javax.Servlet.GenericServletjavax.Servlet.GenericServlet and and javax.Servlet.http.HttpServletjavax.Servlet.http.HttpServlet (for HTTP- (for HTTP-specific requests) classes are implementations specific requests) classes are implementations of the Servlet interface.of the Servlet interface.

Page 8: Servlet

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

88

© Accenture 2005 All Rights Reserved

Servlet ImplementationServlet Implementation

The interfaces The interfaces javax.Servlet.ServletRequestjavax.Servlet.ServletRequest and and ServletResponseServletResponse define the objects that define the objects that provide client request and application response provide client request and application response information to a Servlet. The interfaces information to a Servlet. The interfaces javax.Servlet.http.HttpServletRequestjavax.Servlet.http.HttpServletRequest and and HttpServletResponseHttpServletResponse extend their generic extend their generic counterparts to provide request and response counterparts to provide request and response information for HTTP Servlets. information for HTTP Servlets.

Page 9: Servlet

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

99

© Accenture 2005 All Rights Reserved

Interfaces

Servlet

HttpServletRequest

HttpServletResponse

Servlet Interface

ClassHttpServlet

implements

GenericServlet

Technical Basics of ServletsTechnical Basics of ServletsTechnical Basics of ServletsTechnical Basics of Servlets

Class

Classes

HttpServlet

GenericServlet

extends

Page 10: Servlet

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

1010

© Accenture 2005 All Rights Reserved

Servlet Life CycleServlet Life Cycle

1.1. Loading, Instantiation and InitializationLoading, Instantiation and Initialization The Servlet is loaded into the The Servlet is loaded into the Servlet Container/Web Server.Servlet Container/Web Server. An instance of the Servlet class is created.An instance of the Servlet class is created. The container calls the Servlet’s The container calls the Servlet’s initinit method. The init method method. The init method

is usually overridden to acquire resources.is usually overridden to acquire resources.

2.2. OperationalOperational The container invokes the Servlet’s The container invokes the Servlet’s serviceservice method, passing method, passing

request and response objects.request and response objects. The javax.Servlet.http.HttpServlet class contains more The javax.Servlet.http.HttpServlet class contains more

specialized service methods [such as specialized service methods [such as doGetdoGet and and doPostdoPost] for ] for handling different types of HTTP requests.handling different types of HTTP requests.

Page 11: Servlet

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

1111

© Accenture 2005 All Rights Reserved

Servlet Life CycleServlet Life Cycle

3.3. FinalizationFinalization The container calls the Servlet’s The container calls the Servlet’s destroydestroy

method. Overriding this method releases the method. Overriding this method releases the resources acquired by the Servlet.resources acquired by the Servlet.

Page 12: Servlet

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

1212

© Accenture 2005 All Rights Reserved

init() destroy()

service()requests

loading

unloading

responses

Servlet Life CycleServlet Life CycleServlet Life CycleServlet Life Cycle

Page 13: Servlet

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

1313

© Accenture 2005 All Rights Reserved

Initializing a ServletInitializing a Servlet

The container calls the The container calls the initinit method of the Servlet method of the Servlet once to initialize it. A once to initialize it. A ServletExceptionServletException is thrown is thrown if initialization fails. if initialization fails.

Fortunately, we no longer have to implement this Fortunately, we no longer have to implement this method since the GenericServlet class already has method since the GenericServlet class already has one. In cases where customization is absolutely one. In cases where customization is absolutely necessary, GenericServlet also has an overloaded necessary, GenericServlet also has an overloaded initinit method to further simplify the process – no method to further simplify the process – no need to call need to call super.init(ServletConfig config)super.init(ServletConfig config)..

Page 14: Servlet

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

1414

© Accenture 2005 All Rights Reserved

Initializing a ServletInitializing a Servlet

The following example overrides the overloaded The following example overrides the overloaded initinit method: method:

public class Hello extends HttpServlet {public class Hello extends HttpServlet {

public void init() {public void init() {

System.out.println(“Initializing System.out.println(“Initializing Servlet…"); Servlet…");

}}

}}

Page 15: Servlet

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

1515

© Accenture 2005 All Rights Reserved

Writing Service MethodsWriting Service Methods

The service provided by a Servlet is implemented in the The service provided by a Servlet is implemented in the serviceservice method of a GenericServlet, in the method of a GenericServlet, in the dodoMethodMethod methods (where methods (where MethodMethod can take the value Get, Delete, can take the value Get, Delete, Options, Post, Put, or Trace) of an HttpServlet object or Options, Post, Put, or Trace) of an HttpServlet object or in any other protocol-specific methods defined by a in any other protocol-specific methods defined by a class that implements the Servlet interface.class that implements the Servlet interface.

The The doGetdoGet, , doDeletedoDelete, , doOptionsdoOptions, , doPostdoPost, , doPutdoPut, and , and doTracedoTrace methods are called by the server (via the methods are called by the server (via the serviceservice method) to allow a Servlet to handle GET, method) to allow a Servlet to handle GET, DELETE, OPTIONS, POST, PUT, and TRACE DELETE, OPTIONS, POST, PUT, and TRACE requests respectively.requests respectively.

beverly.rico
Not sure how to make the first bullet more understandable (didn't want to risk compromising important content). So I left it alone but it needs some work.
Page 16: Servlet

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

1616

© Accenture 2005 All Rights Reserved

Maintaning Client StateMaintaning Client State

Web-based applications are responsible for maintaining Web-based applications are responsible for maintaining statestate, called a , called a sessionsession, in order to associate a series of , in order to associate a series of HTTP requests from a client. HTTP requests from a client.

Java Servlet technology provides an API for managing Java Servlet technology provides an API for managing sessions and allows several mechanisms for implementing sessions and allows several mechanisms for implementing sessions.sessions.

Sessions are represented by an Sessions are represented by an javax.Servlet.HttpSessionjavax.Servlet.HttpSession object. object.

The The getSessiongetSession method of request objects is used to method of request objects is used to retrieve the current session associated with this request, or, retrieve the current session associated with this request, or, if the request does not have a session, it creates one. if the request does not have a session, it creates one.

Page 17: Servlet

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

1717

© Accenture 2005 All Rights Reserved

Maintaining Client StateMaintaining Client State

Because there is no way for an HTTP client to signal it Because there is no way for an HTTP client to signal it no longer needs a session, each session has an no longer needs a session, each session has an associated timeout so that its resources can be associated timeout so that its resources can be reclaimed. The timeout period can be accessed by reclaimed. The timeout period can be accessed by using a session's using a session's [get|set]MaxInactiveInterval[get|set]MaxInactiveInterval method. You can also set the timeout period using the method. You can also set the timeout period using the deploy tool. deploy tool.

When a particular client interaction is finished, you use When a particular client interaction is finished, you use the session's the session's invalidateinvalidate method to invalidate a session method to invalidate a session on the server side and remove any session data.on the server side and remove any session data.

Page 18: Servlet

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

1818

© Accenture 2005 All Rights Reserved

Session TrackingSession Tracking A web container can use several methods to associate a A web container can use several methods to associate a

session with a user, all of which involve passing an identifier session with a user, all of which involve passing an identifier between the client and the server. The identifier can be between the client and the server. The identifier can be maintained on the client as a maintained on the client as a cookiecookie (javax.Servlet.http.Cookie), or the web component can (javax.Servlet.http.Cookie), or the web component can include the identifier in every include the identifier in every URLURL that is returned to the that is returned to the client.client.

If your application uses session objects, you must ensure that If your application uses session objects, you must ensure that session tracking is enabled by having the application rewrite session tracking is enabled by having the application rewrite URLs whenever the client turns off cookiesURLs whenever the client turns off cookies. You do this by . You do this by calling the response's calling the response's encodeURL(URL)encodeURL(URL) method on all method on all URLs returned by a Servlet. This method includes the session URLs returned by a Servlet. This method includes the session ID in the URL only if cookies are disabled; otherwise, it ID in the URL only if cookies are disabled; otherwise, it returns the URL unchanged.returns the URL unchanged.

out.println(“...” + out.println(“...” + response.encodeURL(request.getContextPath() + …response.encodeURL(request.getContextPath() + …

Page 19: Servlet

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

1919

© Accenture 2005 All Rights Reserved

Finalizing a ServletFinalizing a Servlet

The container calls the destroy The container calls the destroy method of the Servlet to:method of the Servlet to:– Finalize itFinalize it– Release any resources the Servlet is Release any resources the Servlet is

using using – Save any persistent stateSave any persistent state

Page 20: Servlet

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

2020

© Accenture 2005 All Rights Reserved

Finalizing a ServletFinalizing a Servlet

The server tries to ensure that all of a The server tries to ensure that all of a Servlet's service methods are Servlet's service methods are complete by calling the destroy complete by calling the destroy method only method only afterafter all service requests all service requests have returned or after a server-have returned or after a server-specific grace period has elapsed, specific grace period has elapsed, whichever comes first.whichever comes first.

Page 21: Servlet

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

2121

© Accenture 2005 All Rights Reserved

Finalizing a ServletFinalizing a Servlet

Like the Like the initinit method, the method, the GenericServlet class also has an GenericServlet class also has an implementation for the destroy implementation for the destroy method. The developer must make method. The developer must make sure that all resources taken up in the sure that all resources taken up in the initialization can be released in initialization can be released in calling this method. calling this method.

Page 22: Servlet

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

2222

© Accenture 2005 All Rights Reserved

The following example overrides the The following example overrides the destroydestroy method:method:

public class Hello extends HttpServlet {public class Hello extends HttpServlet {

public void destroy() {public void destroy() {

System.out.println(“Finalizing Servlet.."); System.out.println(“Finalizing Servlet..");

}}

}}

Finalizing a ServletFinalizing a ServletFinalizing a ServletFinalizing a Servlet

Page 23: Servlet

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

2323

© Accenture 2005 All Rights Reserved

Example: A Simple Servlet ClassExample: A Simple Servlet Classimport java.io.*; import javax.Servlet.*;import java.io.*; import javax.Servlet.*;import javax.Servlet.http.*;import javax.Servlet.http.*;public class Hello extends HttpServlet {public class Hello extends HttpServlet { // the doPost method is one of the service methods of HttpServlet // the doPost method is one of the service methods of HttpServlet public void public void doPostdoPost(HttpServletRequest request, HttpServletResponse response)(HttpServletRequest request, HttpServletResponse response) throws throws ServletExceptionServletException, , IOExceptionIOException { { // retrieves the client’s name// retrieves the client’s name String name = request.getParameter("your_name");String name = request.getParameter("your_name"); // displays greeting// displays greeting response.setContentType("text/html");response.setContentType("text/html"); PrintWriter out = response.getWriter();PrintWriter out = response.getWriter();

out.print("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2//EN\">" +out.print("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2//EN\">" + "<html>" +"<html>" + "<head>" +"<head>" + "<title>Servlet Example 1</title>" +"<title>Servlet Example 1</title>" + "</head>" +"</head>" + "<body>" + "<body>" + "<tr><td>Hello " + name + "!</td></tr>" +"<tr><td>Hello " + name + "!</td></tr>" + "</body>" +"</body>" + "</html>"); "</html>"); }} }}

Page 24: Servlet

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

2424

© Accenture 2005 All Rights Reserved

Example: Maintaining SessionExample: Maintaining Session

public class SessionExample extends HttpServlet { public class SessionExample extends HttpServlet {

public void doGet (HttpServletRequest request,public void doGet (HttpServletRequest request,

HttpServletResponse response)HttpServletResponse response)

throws ServletException, IOExceptionthrows ServletException, IOException { {

// Get the user's session and shopping cart// Get the user's session and shopping cart

HttpSession session = request.getSession();HttpSession session = request.getSession();

......

// Invalidate the session// Invalidate the session

session.invalidate();session.invalidate();

}}

}}

Page 25: Servlet

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

2525

© Accenture 2005 All Rights Reserved

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();

}}

Another Servlet ExampleAnother Servlet ExampleAnother Servlet ExampleAnother Servlet Example

Page 26: Servlet

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

2626

© Accenture 2005 All Rights Reserved

SummarySummary

A Servlet is a class that responds to a service request.A Servlet is a class that responds to a service request. It implements the It implements the javax.Servlet.Servlet javax.Servlet.Servlet interface:interface:

– initinit called once to initialize the Servlet called once to initialize the Servlet– serviceservice called to get the Servlet to respond to a client request. called to get the Servlet to respond to a client request.– destroydestroy called at termination (close / deallocate resources) called at termination (close / deallocate resources)

An easier way to do one is Extend the class An easier way to do one is Extend the class javax.Servlet.http.HttpServletjavax.Servlet.http.HttpServlet, which implements this , which implements this interface.interface.– This is an abstract class, so you need to override at least one This is an abstract class, so you need to override at least one

method, which typically is method, which typically is doGet.doGet.

Page 27: Servlet

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

2727

© Accenture 2005 All Rights Reserved

ResourcesResources

Helpful Websites:Helpful Websites: http://java.sun.com/j2ee/1.4/docs/ tutorial/doc/J2http://java.sun.com/j2ee/1.4/docs/ tutorial/doc/J2

EETutorial.pdfEETutorial.pdf

http://java.sun.com/j2ee/1.4/docs/api/ http://java.sun.com/j2ee/1.4/docs/api/ index.htmlindex.html http://faculty.washington.edu/hanks/Courses/460/http://faculty.washington.edu/hanks/Courses/460/

w03/Slides/Tech/03-06-Servlet.pptw03/Slides/Tech/03-06-Servlet.ppt http://www.cs.niu.edu/~jzhou/courses/csci470/Sehttp://www.cs.niu.edu/~jzhou/courses/csci470/Se

rvlet.pptrvlet.ppt http://courses.coreServlets.com/Course-http://courses.coreServlets.com/Course-

Materials/pdf/csajsp2/02-Servlet-Basics.pdfMaterials/pdf/csajsp2/02-Servlet-Basics.pdf

Page 28: Servlet

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

2828

© Accenture 2005 All Rights Reserved

Questions & CommentsQuestions & Comments