Servlets - Mary Robinson CIS285 Instructor Page
Download
Report
Transcript Servlets - Mary Robinson CIS285 Instructor Page
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
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
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
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.
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)
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.
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.
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.
Robinson_CIS285Winter2005
HTTP Flows:
Forms / POST Request
GET (request) HTML document
RequestParamExample.html
Return (response) document
Submit form (POST action) (request)
Client /
Browser
Server returns the HTML document
Generated by the java servlet – based
on the input from the form (response)
Web
Server /
Application
Server
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.
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.0
User-Agent: Mozilla/4.5 [en] (X11; SunOS 5.5.1 sun4m)
Accept: image/gif, image/x-xbitmap, image/jpeg, */*
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.
Robinson_CIS285Winter2005
Server Response May Look
Like This:
HTTP/1.1 200 OK
Date: Mon, 24 Jan 2005 23:33:10 GMT
Server Apache/1.3.1 (Unix)
Last-Modified: Tue, 20 Dec 2004 21:00:15 GMT
Content-Length: 49
Content-Type: text/html
<HTML>
Welcome to the webmaster server…
<HTML>
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
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.
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.
Robinson_CIS285Winter2005
Server Response
1.
2.
3.
4.
5.
Informational. The request was received
and is being processed.
Success. The client request was
successful.
Redirection. The client request was not
performed; further action must be taken
by the client.
Client error. The client’s request was
incomplete or incorrect and cannot be
fulfilled.
Server error. The request was not
fulfilled, due to a server problem
Robinson_CIS285Winter2005
Server Response
Informational 1XX
100 Continue
Success
200 OK
2XX
Redirection
3XX
301 Moved permanently
302 Found (Moved Temporarily
304 Not Modified
Client error
4XX
Server error
5XX
400 Bad Request
403 Forbidden
404 Not Found
500 Internal Server Error
Robinson_CIS285Winter2005
HTTP Flows:
Forms / POST Request
GET (request) HTML document
RequestParamExample.html
Return (response) document
Submit form (POST action) (request)
Client /
Browser
Server returns the HTML document
Generated by the java servlet – based
on the input from the form (response)
Web
Server /
Application
Server
Robinson_CIS285Winter2005
HTTP Flows - HTML
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)
Robinson_CIS285Winter2005
HTTP Protocol Request
POST /example/servlets/RequestParamExample HTTP 1.0
Referrer: http://
Connection: Keep-Alive
User-Agent: Mozilla/4.72 [en (WinNT 5.0; U)]
Host: localhost:8080
Cookie: USERID=spot
Accept: image/gif, image/x-xbitmap, image/jpeg, */*
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Content-type: application/x-www-form-urlencoded
Content-length: 80
Robinson_CIS285Winter2005
HTTP Protocol - Response
Response phase
Status information (200 in example)
Header values
A blank line
Output document (HTML)
Robinson_CIS285Winter2005
HTTP Protocol - Request
HTTP/1.1 200 ok
Content-Type: text/html
Set-Cookie: sessionid=5H2HXGYAAAAEWAAAAZJCI;Path=/
Cache-Control: no-cache=“set-cookie,setcookie2”
Expires: Thu, 26 Dec 1994 16:00:00 GMT
Set-Cookie: USERID=spot; Expires=Fri, 24-Jul-2005 21:30:37
GMT
Accept: image/gif, image/x-xbitmap, image/jpeg, */*
Content-Language: en
<HTML>
<BODY>
<H1>Mary Robinson</H1>
</BODY>
</HTML>
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
Robinson_CIS285Winter2005
Servlet Process Flow
URL
request
Servlet
Instance
response
Browser
(client)
Application
Server
Web
Server
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*
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
Implements
javax.servlet.GenericServlet
javax.servlet.http.HttpServlet
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
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
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
Robinson_CIS285Winter2005
Java Servlet Lifecycle
Methods
Individual servlet lifecycle
Create
Initialize
Unavailable
For service
Available
For service
Destroy
Servicing
requests
Unload
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
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.
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.
Robinson_CIS285Winter2005
Java Servlet Lifecycle
Create
(Initialize failed)
Initialize
Unavailable
For service
Available
For service
(Unavailable
Exception thrown)
Servicing
requests
Destroy
Unload
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)
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
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).
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
Implements
javax.servlet.GenericServlet
javax.servlet.http.HttpServlet
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
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()
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>
Robinson_CIS285Winter2005
Example Servlet:
With Init Parameters
// servlets init method
public void init() {
String maxTries;
string autoSave;
maxTries = getInitParameter(“MaxTries”);
autoSave = getInitParameter(“AutoSave”);
// process the parameters
….
}
Robinson_CIS285Winter2005
Example Servlet:
With Init Parameters
// servlets init method
public void init() {
ServletConfig config = getServletConfig();
String maxTries;
string autoSave;
maxTries = config.getInitParameter(“MaxTries”);
autoSave = config.getInitParameter(“AutoSave”);
// process the parameters
….
}
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()
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.
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
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
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
Robinson_CIS285Winter2005
Response Protocol
setContentType(String type)
getWriter()
Set the content type for this response
Type is a MIME type
Returns a reference to the PrintWriter
getOutputStream()
Returns a reference to the
ServletOutputStream
Used to create binary documents
Robinson_CIS285Winter2005
Single-Threaded Servlets
By default servlets must support multiple
threads of execution
Servlets can be forced to be singlethreaded 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
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.
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
Robinson_CIS285Winter2005
MVC: Model, View, Controller
Model 1
Model 2
Blatantly “borrowed” from
Robinson_CIS285Winter2005
http://www.javaworld.com/javaworld/jw-12-1999/jw-12-ssj-jspmvc_p.html
Servlet Architecture
Geared towards one goal:
PERFORMANCE
Robinson_CIS285Winter2005