57
Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Embed Size (px)

Citation preview

Page 1: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

Servlets

CIS 28525 January 2005Mary Robinson

Page 2: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

What is a Servlet

Pure Java alternative to CGI Java technology that runs in the

server tier Dynamic Exists in the “layer” between

browser and database applications

Page 3: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

Servlets

A web component written in java, whose purpose is the generation of dynamic content

Its execution and lifecycle are managed by a Web container within an application server.

Can interact with Web clients indirectly via the container, using HTTP request-response protocol.

Client, via web browser, can invoke a servlet: Entering a URL in the browser Clicking a hypertext link Submitting an HTML form

Page 4: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

How Do I Run Servlets ?

Need a Web container (servlet container is no longer required

Tomcat (Apache), WebSphere, BEA Web Logic, JRUN

Some servlet reference implementations are still free

Can be run standalone Can be integrated with Web server:

Apache IIS, IES(nee NES) and so forth

Page 5: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

Why Use Servlets?

Easier to program Servlets all share the same structure and basic

method calls – easier to code Servlet classes provide parsing and decoding of

input data Support for session tracking Support for cookies

Little training is required to write servlets. J2EE compliant – just need to follow the

J2EE specifications and servlets should run correctly.

Page 6: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

Why Use Servlets?

Better use of system resources CGI starts a new process for each HTTP request For each Java Servlet, each new request for a

specific servlet starts a new thread of execution Java Portability

Write once, run anywhere Supported by many application servers Part of Java 2 Platform (J2EE)

Page 7: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

Why Use Servlets? Type checking

Java is a typed language Exception handling allows for robust error

handling JVM protect the system from Java coding issues For each Java Servlet, each new request for a

specific servlet starts a new thread of execution Security

Runs in the Web container Can restrict servlet access Can be part of a Single (global) Sign On security

architecture.

Page 8: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

Using Servlets

Servlets extend function of server to include server-side programming as a java class.

May do anything the Web server cannot inherently do: Query a database Perform calculations such as tax on purchases

Servlets are portable and runtime environment is standardized, therefore the application server’s handling of requests is also standardized.

Page 9: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

HTTP Transaction

HTTP is a protocol that allows Web browsers to talk to servers and exchange information

HTTP provides a standard way of communicating between browsers and servers

HTTP expects the client to initiate a request and the server to respond.

Page 10: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

HTTP Flows: Forms / POST Request

GET (request) HTML documentRequestParamExample.html

Return (response) document

Submit form (POST action) (request)

Server returns the HTML documentGenerated by the java servlet – based on the input from the form (response)

Client / Browser

WebServer / ApplicationServer

Page 11: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

Initiating an HTTP Response

Request line. This line contains a request method, the document location, and the protocol version.

Header section. This series of lines contains HTTP headers that are used to pass other information about the request, and about the client itself, to the server. A blank line then separates the header section from the entity body.

Entity body. This section contains other data to be passed to the server. There is usually information here only when a form is submitted.

Page 12: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

Transaction Example

If we typed the URL into Netscape: http://webmaster.merrimack.edu/simple.html

The browser would issue an HTTP request similar to the following:

GET /simple.html HTTP/1.0User-Agent: Mozilla/4.5 [en] (X11; SunOS 5.5.1 sun4m)Accept: image/gif, image/x-xbitmap, image/jpeg, */*

Page 13: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

Transaction Example

The server then responds to the request in a similar fashion:

Status line. This line contains the protocol version, a status code, and a reason phrase.

Header section. This series of lines contains HTTP headers that are used to pass other information about the response, and about the server itself, to the client. A blank line then separates the header section from the entity body.

Entity body. This section, if present, contains the document (or object) requested.

Page 14: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

Server Response May Look Like This:

HTTP/1.1 200 OKDate: Mon, 24 Jan 2005 23:33:10 GMTServer Apache/1.3.1 (Unix)Last-Modified: Tue, 20 Dec 2004 21:00:15 GMTContent-Length: 49Content-Type: text/html

<HTML>Welcome to the webmaster server…<HTML>

Page 15: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

Request Methods

Request line of a client request that contains an HTTP command called a request method

Defines what server does with the request

Currently several methods are defined by HTTP 1.1 standard

Only a few are widely supported by HTTP servers

Page 16: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

Methods

HEAD Method The HEAD method is identical to the GET method

except that the server does not return a document; it returns only the header section for the request. The HEAD method is useful for verifying that a document exists for checking links or to get information about the file type and modification time only.

POST Method The POST method allows the server to receive

data from the client. It is most commonly used to send the data in HTML forms to the server for processing. This method passes data to the server in the entity body of the request.

Page 17: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

Other Methods

PUT method is becoming more widely supported. It is used for publishing documents to the Web server from a client. Many of the latest HTML authoring packages support posting documents to a Web server via the PUT method.

DELETE method is used to remove a document from a Web server.

Page 18: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

Server Response

1. Informational. The request was received and is being processed.

2. Success. The client request was successful.

3. Redirection. The client request was not performed; further action must be taken by the client.

4. Client error. The client’s request was incomplete or incorrect and cannot be fulfilled.

5. Server error. The request was not fulfilled, due to a server problem

Page 19: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

Server Response

Informational 1XX 100 Continue

Success 2XX 200 OK

Redirection 3XX 301 Moved permanently 302 Found (Moved Temporarily 304 Not Modified

Client error 4XX 400 Bad Request 403 Forbidden 404 Not Found

Server error 5XX 500 Internal Server Error

Page 20: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

HTTP Flows: Forms / POST Request

GET (request) HTML documentRequestParamExample.html

Return (response) document

Submit form (POST action) (request)

Server returns the HTML documentGenerated by the java servlet – based on the input from the form (response)

Client / Browser

WebServer / ApplicationServer

Page 21: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

HTTP Flows - HTML

Page 22: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

HTTP Protocol Request

Conversation between a browser and a server Request phase

Request (POST in this example) Header values A blank line Posted data (when request method is

POST)

Page 23: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

HTTP Protocol Request

POST /example/servlets/RequestParamExample HTTP 1.0Referrer: http://Connection: Keep-AliveUser-Agent: Mozilla/4.72 [en (WinNT 5.0; U)]Host: localhost:8080Cookie: USERID=spotAccept: image/gif, image/x-xbitmap, image/jpeg, */*Accept-Language: enAccept-Charset: iso-8859-1,*,utf-8Content-type: application/x-www-form-urlencodedContent-length: 80

Page 24: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

HTTP Protocol - Response

Response phase Status information (200 in example) Header values A blank line Output document (HTML)

Page 25: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

HTTP Protocol - Request

HTTP/1.1 200 okContent-Type: text/htmlSet-Cookie: sessionid=5H2HXGYAAAAEWAAAAZJCI;Path=/Cache-Control: no-cache=“set-cookie,setcookie2”Expires: Thu, 26 Dec 1994 16:00:00 GMTSet-Cookie: USERID=spot; Expires=Fri, 24-Jul-2005 21:30:37

GMTAccept: image/gif, image/x-xbitmap, image/jpeg, */*Content-Language: en

<HTML><BODY><H1>Mary Robinson</H1></BODY></HTML>

Page 26: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

Servlet Process Flow

Client makes a request naming a servlet as part of the URL

Web server forward request to Servlet engine (Web container

Servlet engine locates instance of a Servlet class

Servlet engine calls Servlet’s service method

Servlet builds response dynamically and passes it to Web server

Web server sends the response back to the client

Page 27: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

Servlet Process Flow

Browser(client)

WebServer

ApplicationServer

ServletInstance

URL request

response

Page 28: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

What is a Servlet ?

Servlets, as the name implies, are service requests

The servlet API is a set of java classes which define a standard interface between a Web client and a Web server

Servlet API includes two packages javax.servlet* javax.servlet.http*

Page 29: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

Java Servlet API

The servlet API is a set of Java classes that implement one of the interfaces defined in the javax.servlet* or javax.servlet.http*

javax.servlet.Servlet

javax.servlet.GenericServlet

javax.servlet.http.HttpServlet

Implements

Page 30: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

Servlet Process

Servlets are deployed or loaded into a servlet container

The container invokes method callbacks On servlets methods during different

stages of its lifecycle When a client requests service

Page 31: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

Process Flow

Client (Web browser) initiates call to the servlet

Web browser sends HTTP request to Web server

Web server determines content – dynamic for a servlet

Web server forward request to application server, again using HTTP, to an embedded HTTP server

Page 32: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

Process Flow Continued

The Web container within the application server handles communication with the servlet, passing the request and response as objects

Servlet is Java code with standard Java interfaces. Example: Servlet may collaborate with other classes and

objects to accomplish work such as database queries Servlet has answer for client and formats the

answer in HTML dynamically Directly Indirectly – JSP’s

Page 33: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

Java Servlet Lifecycle Methods

Individual servlet lifecycle

Create

Initialize

AvailableFor service

Servicingrequests

Unavailable For service

Destroy

Unload

Page 34: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

Servlet Lifecycle Methods

Basic interface, javax.servlet.Servlet, defines a set of five methods that have to be implemented to provide a service and for the lifecycle methods init service

• doGet• doPost

destroy Individual servlet lifecycle

Page 35: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

Servlet Lifecycle

The lifecycle of a servlet is expressed in the Java servlet API: in the init service (doGet or doPost) destroy methods of the Servlet

interface.

Page 36: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

Life Cycle

Web server passes request to application server

Application server uses a JVM to execute the servlet

JVM allows a servlet to handle multiple requests simultaneously on separate lightweight threads of execution

Over head of loading and starting servlet is significantly reduced to one occurrence

Application server keeps servlet in memory waiting for another request.

Page 37: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

Java Servlet Lifecycle

Create

Initialize

AvailableFor service

Servicingrequests

Unavailable For service

Destroy

Unload

(Unavailable Exception thrown)

(Initialize failed)

Page 38: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

Servlet Creation

Servlets are loaded and instantiated When the container is started When the container determines the

servlets are needed to service requests(first requests)

Page 39: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

Servlet Initialization

Before servlet can handle requests from clients

Perform one-time activities and initialize costly resources

Init() method performs servlet initialization such as loading default data parameters

Two init() methods One takes no input parameters Other takes a ServletConfig reference as a

parameter

Page 40: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

Servlet Request Handling

Accept client requests and send responses back via the Web server.

Service(), doGet(), doPost()..methods are called in response to clients (each HTTP request is on a different thread).

Default service() method calls the doGet() method whenever an HTTP GET request is sent by the Web client (usually a URL).

The doPost() method is called whenever an HTTP POST request is sent by the Web browser client(usually action in HTML form).

Page 41: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

Java Servlet API

The servlet API is a set of Java classes that implement one of the interfaces defined in the javax.servlet* or javax.servlet.http*

javax.servlet.Servlet

javax.servlet.GenericServlet

javax.servlet.http.HttpServlet

Implements

Page 42: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

Servlets and HTTP

Most servlets are used in a Web environment where HTTP is used between a Web client (browser) and the Web server/application server

Much of the standard processing must take place in this HTTP-based environment is managed by javax.servlet.http.HttpServlet

Typical servlet will extend this class and override one or more of the standard methods Ex. doGet() or doPost() to supply specific

servlet behavior

Page 43: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

ServletConfig & Initialization Parameters

The ServletConfig is used by the servlet container to pass information to the servlet during initialization

Accessed via the GenericServlet method getServletConfig()

ServletConfig: Contains initialization parameters as a set of

name/value pairs.• public String getInitParameter (String name)• public Enumeration getInitParameterNames()

Maintains a reference to the servletContext object which gives the servlet information about the serve

• Public ServletContext getServletContext()

Page 44: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

Servlet Definition web.xml File

<servlet><servlet-name>RegistrationServlet</servlet-name> <display-name>RegistrationServlet</display-name>

<servlet-class>com.ibm.ils.exam.servlet.RegistrationServlet<servlet-class>

<init-param><param-name>MaxTries</param-name><param-value>4</param-value>

</init-param><init-param>

<param-name>MaxTries</param-name><param-value>4</param-value>

</init-param><load-on-startup>1</load-on-startup>

</servlet><servlet-mapping>

<servlet-name>RegistrationServlet</servlet-name><url-pattern>Register</url-pattern>

</servlet-mapping>

Page 45: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

Example Servlet: With Init Parameters

// servlets init methodpublic void init() {

String maxTries;string autoSave;maxTries = getInitParameter(“MaxTries”);autoSave = getInitParameter(“AutoSave”);// process the parameters….

}

Page 46: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

Example Servlet: With Init Parameters

// servlets init methodpublic void init() {

ServletConfig config = getServletConfig();String maxTries;string autoSave;maxTries = config.getInitParameter(“MaxTries”);autoSave = config.getInitParameter(“AutoSave”);// process the parameters….

}

Page 47: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

HTTPServlet

An HTTP-specific request handler Adds HTTP specific methods

doGet() – handle a GET request (URL) doPost() – handle a POST request(HTML

form) Subclasses override the doGET,

doPost, and so forth, methods and may override init() and destroy()

doGet() and doPost() do the work and are called by service()

Page 48: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

Requests and Responses

The service(), doGet() and doPost() methods each have two parameters: HttpServletRequest – provides access to request

data (parameters), HttpSession information, and so forth.

HttpServletResponse – provides services to allow the servlet to supply a response to the requesting client.

Most servlet programming involves reading a request and writing a response.

Page 49: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

HttpServlet Request

Represents client’s request Getters for aspects of request, for

example: Request header, content type, length, method Request URL as a String and request servlet

“path” Client security type Access request parameters by name

Possible scope for object sharing among participants satisfying the request

Page 50: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

Request Protocol

The request object encapsulates all information from the client request. The following methods are available to access parameters: getParameterNames()

• Returns an enumeration of parameters on the HTML page

getParameterValues(String name)• Returns the value of a multivalued parameter

getParameter(String name)• Returns the value of a specific named parameter

getReader()• Returns a BufferedReader to view input

Page 51: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

HttpServletResponse

Represents communication channel back to client

Sets the content type and status code Sets content headers (cookies, caching,

and so forth) Allows servlet to return dynamic

content or error information Redirects client to another URL

Page 52: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

Response Protocol

setContentType(String type) Set the content type for this response Type is a MIME type

getWriter() Returns a reference to the PrintWriter

getOutputStream() Returns a reference to the

ServletOutputStream Used to create binary documents

Page 53: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

Single-Threaded Servlets

By default servlets must support multiple threads of execution

Servlets can be forced to be single-threaded if they implement the SingleThreadModel interface. The application server guarantees that no more

than one request thread will simultaneously access an instance of a servlet

Page 54: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

Single-Threaded Servlets

Any single-threaded servlet can be considered thread safe and is not required to synchronize access to its instance variable, but the ruled must be followed: Must still carefully manage any non-final

instance and class fields Shared memory and resources must be locked Possible needs for synchronized methods

Usually performs poorly and should be avoided.

Page 55: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

Java Servlet

Extends javax.servlet.http.HttpServlet Override the doGet or doPost methods

to process HTTP GET or POST requests Process HttpServletRequest input values Invoke the business process Set the HttpServlet Response values Output HTML to the output PrintWriter-

Servlets are inherently multithreaded

Page 56: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

MVC: Model, View, Controller

Blatantly “borrowed” fromhttp://www.javaworld.com/javaworld/jw-12-1999/jw-12-ssj-jspmvc_p.html

Model 1

Model 2

Page 57: Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson

Robinson_CIS285Winter2005

Servlet Architecture

Geared towards one goal:PERFORMANCE