Download Enhancing a Web Server with Servlets

Document related concepts
no text concepts found
Transcript
Enhancing a Web Server
with Servlets
Servlets
• Here focus on both sides of a client-server
relationship.
• The client requests that some action be performed
and the server performs the action and responds
to the client.
• This request-response model of communication is
the foundation for the highest-level view of
networking in Java—servlets.
Servlets
• A common implementation of the requestresponse model is between World Wide Web
browsers and World Wide Web servers.
• When a user selects a Web site to browse through
their browser (the client application), a request is
sent to the appropriate Web server (the server
application).
• The server normally responds to the client by
sending the appropriate HTML Web page.
Servlets
• A servlet extends the functionality of a
server. The javax.servlet package
and the javax.servlet.http
package provide the classes and interfaces
to define servlets.
Servlets
• Servlet technology today is primarily designed
for use with the HTTP protocol of the Web, but
servlets are being developed for other
technologies.
• Servlets are effective for developing Web-based
solutions that help provide secure access to a
Web site, that interact with databases on behalf of
a client, ...
Servlets
• ... that dynamically generate custom
HTML documents to be displayed by
browsers and that maintain unique session
information for each client.
Servlets
• Many developers feel that servlets are the
right solution for database-intensive
applications that communicate with socalled thin clients—applications that
require minimal client-side support.
Servlets
• The server is responsible for the database
access. Clients connect to the server using
standard protocols available on all client
platforms.
• Thus, the logic code can be written once
and reside on the server for access by
clients.
Servlets
• Our servlet example will make use of
JDBC (Java Database Connectivity)
database facilities to build a multi-tier
client-server application that access a
database.
Servlets
• The Servlet APIs are now developed by the
Apache group (www.apache.org).
• Before you can program with servlets, you must
download and install the Apache group's
implementation of servlets called Tomcat.
• You may download Tomcat at no charge from
Sun Microsystems at the Web site:
java.sun.com/products/jsp/tomcat
Servlets
• You may download Tomcat at no charge
from Sun Microsystems at the Web site:
java.sun.com/products/jsp/tom
cat
Servlets
• After downloading Tomcat, install it on
your system and carefully read the
readme file supplied in the doc directory.
• It explains how to set up Tomcat and
discusses how to start the server that can
be used to test servlets if you do not have a
Web server that supports servlets.
Servlets
• To develop servlets, you also need to copy
the servlet.jar file containing the
servlet class files from the installation
directory to your JDK extensions directory
(the directory
c:\jdk1.3\jre\lib\ext on
Windows or the directory
~/jdk1.3/jre/lib/ext on UNIX).
Overview of Servlet Technology
• Servlets are the analog on the server side to
applets on the client side. Servlets are
normally executed as part of a Web server.
• In fact, servlets have become so popular
that they are now supported by most major
Web servers, ...
Overview of Servlet Technology
• ... including the Netscape Web servers,
Microsoft's Internet Information Server
(IIS), the World Wide Web Consortium's
Jigsaw Web server and the popular Apache
Web server.
Overview of Servlet Technology
• The servlets in this chapter show the
communication between clients and servers via
the HTTP protocol of the World Wide Web.
• A client sends an HTTP request to the server. The
server receives the request and directs it to be
processed by appropriate servlets.
Overview of Servlet Technology
• The servlets do their processing (which
often includes interacting with a database),
then return their results to the client—
normally in the form of HTML documents
to display in a browser, but other data
formats, such as images and binary data,
can be returned.
The Servlet API
The Servlet API
• We discuss at a high level the servlet-related
classes, methods and exceptions. Architecturally,
all servlets must implement the Servlet
interface.
• The methods of interface Servlet are invoked
automatically (by the server on which the servlet
is installed).
The Servlet API
• The servlet packages define two
abstract classes that implement the
interface Servlet—class
GenericServlet (from the package
javax.servlet) and class
HttpServlet (from the package
javax.servlet.http).
The Servlet API
• These classes provide default implementations of
all the Servlet methods.
• Most servlets extend either GenericServlet
or HttpServlet and override some or all of
their methods with appropriate customized
behaviors.
Servlets
Methods of
Interface Servlet
Method
Description
• void init( ServletConfig
config )
• This method is automatically called once
during a servlet's execution cycle to
initialize the servlet. The
ServletConfig argument is supplied
automatically by the server that executes
the servlet.
Method
Description
• ServletConfig getServletConfig()
• This method returns a reference to an object that
implements interface ServletConfig. This
object provides access to the servlet's
configuration information such as initialization
parameters and the servlet's ServletContext,
which provides the servlet with access to its
environment (i.e., the server in which the servlet
is executing).
Method
Description
• void service( ServletRequest
request,
ServletResponse response )
• This is the first method called on every
servlet to respond to a client request.
Method
Description
• String getServletInfo()
• This method is defined by a servlet
programmer to return a String
containing servlet information such as the
servlet's author and version.
Method
Description
• void destroy()
• This "cleanup" method is called when a servlet is
terminated by the server on which it is executing.
• This is a good method to use to deallocate a
resource used by the servlet (such as an open file
or an open database connection).
The Servlet API
• The example we present extends class
HttpServlet, which defines enhanced
processing capabilities for servlets that extend the
functionality of a Web server.
• The key method in every servlet is method
service, which receives both a
ServletRequest object and a
ServletResponse object.
The Servlet API
• These objects provide access to input and
output streams that allow the servlet to
read data from the client and ...
• ... send data to the client. These streams
can be either byte-based streams or
character-based streams.
The Servlet API
• If problems occur during the execution of a
servlet, either ServletExceptions or
IOExceptions are thrown to indicate
the problem.
HttpServlet Class
HttpServlet Class
• Web-based servlets typically extend the
class HttpServlet.
• This class HttpServlet overrides the
method service to distinguish between
the typical requests received from a client
Web browser.
HttpServlet Class
• The two most common HTTP request types
(also known as request methods) are get
and post.
• A get request gets (or retrieves)
information from the server.
• Common uses of get requests are to
retrieve an HTML document or an image.
HttpServlet Class
• A post request posts (or sends) data to the
server.
• Common uses of post requests are to send the
to Web-server, information from an HTML form
in which the client enters data, ...
• ... to send to the server, information so that it can
search on the Internet, ...
• ... or query a database for the client, ...
• ... to send authentication information to the
server, etc.
HttpServlet Class
• The class HttpServlet defines the methods
doGet and doPost, which respond to get and
post requests from a client,respectively.
• These methods are called by the HttpServlet
class's service method, which is called when a
request arrives at the server.
• The method service first determines the
request type, then calls the appropriate method.
HttpServlet Class
• Methods doGet and doPost receive as
arguments an HttpServletRequest
object and an HttpServletResponse
object that enable interaction between the
client and the server.
HttpServlet Class
• The methods of HttpServletRequest
make it easy to access the data supplied as
part of the request.
• The HttpServletResponse methods
make it easy to return the servlet's results
in HTML format to the Web client.
HttpServlet Class
• The interfaces HttpServletRequest
and HttpServletResponse are
discussed now.
HttpServletRequest
Interface
Important methods of interface
HttpServletRequest
Method
Descriptions
HttpServletRequest
Interface
• Every call to doGet or doPost for an
HttpServlet receives an object that
implements interface HttpServletRequest.
• The Web server that executes the servlet creates
an HttpServletRequest object and passes
this to the servlet's service method (which, in
turn, passes it to doGet or doPost).
HttpServletRequest
Interface
• This object contains the request from the
client. A variety of methods are provided to
enable the servlet to process the client's
request. Some of these methods are from
interface ServletRequest—the
interface that HttpServletRequest
extends.
HttpServletRequest
Interface
• String getParameter( String
name )
• Returns the value associated with a
parameter sent to the servlet as part of a
GET or POST request. The name argument
represents the parameter name.
HttpServletRequest Interface
• Enumeration
getParameterNames()
• Returns the names of all the parameters
sent to the servlet as part of a POST
request
HttpServletRequest Interface
• String[] getParameterValues(
String name )
• Returns a String array containing the
values for a specified servlet parameter.
HttpServletRequest Interface
• Cookie[] getCookies()
• Returns an array of Cookie objects stored
on the client by the server. Cookies can
be used to uniquely identify clients to the
servlet.
HttpServletRequest Interface
• HttpSession getSession( boolean
create )
• Returns an HttpSession object associated
with the client's current browsing session.
• An HttpSession object can be created by this
method (true argument) if an HttpSession
object does not already exist for the client.
• HttpSession objects can be used in similar
ways to Cookies for uniquely identifying
HttpServletResponse
Interface
Important methods of interface
HttpServletResponse
Method
Descriptions
HttpServletResponse Interface
• Every call to doGet or doPost for an
HttpServlet receives an object that
implements interface
HttpServletResponse.
• The Web server that executes the servlet creates
an HttpServletResponse object and passes
this to the servlet's service method (which, in
turn, passes it to doGet or doPost).
HttpServletResponse Interface
• This object contains the response to the
client. A variety of methods are provided to
enable the servlet to formulate the response
to the client. Some of these methods are
from interface ServletResponse—the
interface that HttpServletResponse
extends.
HttpServletResponse Interface
• A few key methods used in this interface
are presented as follow:
HttpServletResponse Interface
• void addCookie( Cookie cookie
)
• Used to add a Cookie to the header of the
response to the client. The Cookie's
maximum age and whether the client
allows Cookies to be saved determine
whether or not Cookies will be stored on
the client.
HttpServletResponse Interface
• ServletOutputStream
getOutputStream()
• Obtains a byte-based output stream enabling
binary data to be sent to the client.
• PrintWriter
getWriter()
• Obtains a character-based output stream enabling
text data to be sent to the client.
HttpServletResponse Interface
• void setContentType( String type )
• Specifies the MIME type of the response to the
browser. The MIME type helps the browser
determine how to display the data (or possibly
what other application to execute to process the
data).
• For example, MIME type "text/html"
indicates that the response is an HTML
document, so the browser displays the HTML
page.
Multi-tier Client/Server Application
with Servlets
Multi-tier Client/Server Application
with Servlets
• Servlets can communicate with databases via
JDBC (Java Database Connectivity).
• JDBC provides a uniform way for a Java
program to connect with a variety of databases in
a general manner without having to deal with the
specifics of those database systems.
Multi-tier Client/Server Application
with Servlets
• Many of today's applications are three-tier
distributed applications, consisting of a
user interface, business logic and database
access.
• The user interface in such an application is
often created using HTML (as shown in
this chapter) or Dynamic HTML.
Multi-tier Client/Server Application
with Servlets
• In some cases, Java applets are also used for this
tier.
• HTML is the preferred mechanism for
representing the user interface in systems where
portability is a concern.
• Because HTML is supported by all browsers,
designing the user interface to be accessed
through a Web browser guarantees portability
across all platforms that have browsers.
Multi-tier Client/Server Application
with Servlets
• Using the networking provided automatically by
the browser, the user interface can communicate
with the middle-tier business logic.
• The middle tier can then access the database to
manipulate the data. All three tiers may reside on
separate computers that are connected to a
network.
Multi-tier Client/Server Application
with Servlets
• In multi-tier architectures, Web servers are
increasingly used to build the middle tier.
• They provide the business logic that
manipulates data from databases and that
communicates with client Web browsers.
Multi-tier Client/Server Application
with Servlets
• Servlets, through JDBC, can interact with
popular database systems.
• Developers do not need to be familiar with the
specifics of each database system.
• Rather, developers use SQL-based queries and
the JDBC driver handles the specifics of
interacting with each database system.
Multi-tier Client/Server Application
with Servlets
• The servlet of Fig 27.32 (a servlet) and the
HTML document of Fig 27.33 (the client)
show a three-tier distributed application
that displays the user interface in a browser
using HTML.
Multi-tier Client/Server Application
with Servlets
• The middle tier is a Java servlet that
handles requests from the client browser
and provides access to the third tier—a
Microsoft Access database (set up as an
ODBC data source) accessed via JDBC.
Multi-tier Client/Server Application
with Servlets
• The servlet in this example is a guest book servlet
that allows the user to register for several
different mailing lists.
• When the servlet receives a post request from
the HTML document of Fig 27.33, it ensures that
the required data fields are present, then stores
the data in the database and sends a confirmation
page to the client.
Multi-tier Client/Server Application
with Servlets
• The class GuestBookServlet extends class
HttpServlet (line 9) so it is capable of
responding to GET and POST requests.
• Servlets are initialized by overriding method
init (line 14).
• Method init is called exactly once in a servlet's
lifetime and is guaranteed to complete before any
client requests are accepted.
Multi-tier Client/Server Application
with Servlets
• The method init takes a ServletConfig
argument and throws a ServletException.
• The argument provides the servlet with
information about its initialization parameters
(i.e., parameters not associated with a request, but
passed to the servlet by the Web server for
initializing servlet variables).
Multi-tier Client/Server Application
with Servlets
• In this example, the servlet's init method
performs the connection to the Microsoft Access
database.
• The method loads the JdbcOdbcDriver at
line 20 with:
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
Multi-tier Client/Server Application
with Servlets
• Lines 21 and 22
connection =
DriverManager.getConnection( URL, "", "" );
• attempt to open a connection to the
Guests database.
Multi-tier Client/Server Application
with Servlets
• The string jdbc:odbc:Guests stored in URL
specifies the database URL (Uniform Resource
Locator) that helps the program locate the
database (possibly on a network or in the local
file system of the computer).
• The URL specifies the protocol for
communication (jdbc), the subprotocol for
communication (odbc) and the name of the
database (Guests).
Multi-tier Client/Server Application
with Servlets
• The URL specifies the protocol for
communication (jdbc), the subprotocol for
communication (odbc) and the name of the
database (Guests).
• The subprotocol odbc indicates that the program
will be using jdbc to connect to a Microsoft
ODBC data source (see appendix H for
information on setting up an ODBC data source).
Multi-tier Client/Server Application
with Servlets
• ODBC is a technology developed by Microsoft to
allow generic access to disparate database
systems on the Windows platform (and some
UNIX platforms).
• The Java 2 Software Development Kit (J2SDK)
comes with the JDBC-to-ODBC-bridge database
driver to allow any Java program to access any
ODBC data source.
Multi-tier Client/Server Application
with Servlets
• The driver is defined by class
JdbcOdbcDriver in package
sun.jdbc.odbc. The second and third
arguments to getConnection represent
the username and password (in this
example the database does not have a
username and password).
Multi-tier Client/Server Application
with Servlets
• Lines 23-25
statement = connection.prepareStatem
ent(
"INSERT INTO Guests values ( " +
"?, ?, ?, ?, ?, ?, ?, ? );" );
• create a PreparedStatement that will
be used to insert a record into the database.
Multi-tier Client/Server Application
with Servlets
• The question mark characters in the string represent the
placeholders for values that will be inserted.
• These values are specified with PreparedStatement
set method calls before executing the insert operation.
• The eight placeholders in this example represent the
user's email address, first name, last name, company and
the four mailing lists the user would like to register to
receive.
Multi-tier Client/Server Application
with Servlets
• When a post request is received from the
HTML document in Fig 27.33, method doPost
(line 33) responds by reading the HTML form
field values from the post request, setting the
parameters for the INSERT INTO operation on
the database (lines 54-65) and executing the
insert operation (line 66).
• Line 67 closes the statement to ensure that
the insert operation is committed to the database.
Multi-tier Client/Server Application
with Servlets
• The if structure at lines 44-50 determines if the
email, first name or last name parameters are
empty Strings. If so, the servlet response asks
the user to return to the HTML form and enter
those fields.
• Line 83 defines method destroy to ensure that
the database connection is closed before the
servlet terminates.
Multi-tier Client/Server Application
with Servlets
• Figure 27.33 defines the HTML document
that presents the guest book form to the
user and POSTs the information to the
servlet of Fig 27.32.
Multi-tier Client/Server Application
with Servlets
• Lines 9-11 specify that the form's action is to
post information to the GuestBookServlet.
• The screen captures show the form filled with
one set of information (the first screen) and the
confirmation Web page that was sent back to the
client as the response to the post request.
Servlets
Server-Side Java Programming
Servlets and Server-Side Java
Programming
• java.sun.com/products/servlet/index.ht
ml
• The servlet page at the Sun Microsystems, Inc.
• Java Web site provides access to the latest servlet
information, servlet resources and the Java
Servlet Development Kit (JSDK).
Servlets and Server-Side Java
Programming
• theserverside.com/home/index.
jsp
• This Web site is an excellent resource for
anyone doing server-side Java
development and development with the
Java 2 Enterprise Edition.
Servlets and Server-Side Java
Programming
• www.servlets.com
This is the Web site for the book Java Servlet
Programming published by O'Reilly.
• The book provides a variety of resources.
• This book is an excellent resource for
programmers who are learning servlets.
Servlets and Server-Side Java
Programming
• www.servletcentral.com
Servlet Central is an online magazine for serverside Java programmers.
• This includes technical articles and columns,
news and "Ask the Experts."
• Resources include: books, servlet documentation
links on the Web, a servlet archive, a list of
servlet-enabled applications and servers and
servlet development tools.
Servlets and Server-Side Java
Programming
• http://www.servletsource.com/
is a general servlet resource site containing code,
tips, tutorials and links to many other Web sites
with information on servlets.
• http://www.cookiecentral.com/
A good all-around resource site for cookies.
Servlets and Server-Side Java
Programming
• www.purpletech.com/java/servl
et-faq/
The Purple Servlet FAQ is a great resource
with dozens of links to tutorials, other
servlet FAQs, mailing lists and
newsgroups, articles, web servers,
whitepapers and Java e-mail resources.
Servlets and Server-Side Java
Programming
• http://www.servletforum.com/
is an on-line newsgroup dedicated to Java
Servlets. Post your own questions or check
out the archived list of previously asked
questions.
Servlets and Server-Side Java
Programming
• www.enhydra.org/
Enhydra is an open source Java/XML application
server and development environment available
for free download.
• www.locomotive.org/locolink/disp?
home
The Locomotive Project is an open source,
servlet-compatible, web application server
available for free download.
Servlets and Server-Side Java
Programming
• www.servlet.com/srvpages/srvd
ev.html
• The Servlet, Inc. Servlet Developer's
Forum has links to numerous web
resources, examples, products that use
servlets and server-enabled web servers.
Summary
About Servlets
Summary about Servlets
• The request-response model of
communication is the foundation for the
highest-level view of networking in Java—
servlets.
• A servlet extends the functionality of a
server.
Summary about Servlets
• The javax.servlet package and the
javax.servlet.http package
provide the classes and interfaces to define
servlets.
Summary about Servlets
• A common implementation of the requestresponse model is between World Wide Web
browsers and World Wide Web servers.
• When a user selects a Web site to browse through
their browser (the client application), a request is
sent to the appropriate Web server (the server
application).
• The server normally responds to the client by
sending the appropriate HTML Web page.
Summary about Servlets
• All servlets must implement the Servlet
interface. The methods of interface
Servlet are invoked automatically (by
the server on which the servlet is installed).
• An HttpServlet defines enhanced
processing capabilities for servlets that
extend the functionality of a Web server.
Summary about Servlets
• Class HttpServlet overrides method
service to distinguish between the
typical requests received from a client Web
browser.
• The two most common HTTP request
types (also known as request methods) are
get and post.
Summary about Servlets
• Class HttpServlet defines methods doGet
and doPost to respond to get and post
requests from a client, respectively.
• Servlets can communicate with databases via
JDBC (Java Database Connectivity).
• JDBC provides a uniform way for a Java
program to connect with a variety of databases in
a general manner without having to deal with the
specifics of those database systems.
Summary about Servlets
• To connect to a database, you must first
load the database driver, then connect to
the database with class
DriverManager's getConnection
method.
• The URL to connect to a database specifies
the protocol for communication, the
subprotocol for communication and the
name of the database.
Summary about Servlets
• The subprotocol odbc indicates that the
program will be using jdbc to connect to
a Microsoft ODBC data source.
• ODBC is a technology developed by
Microsoft to allow generic access to
disparate database systems on the
Windows platform (and some UNIX
platforms).
Summary about Servlets
• A PreparedStatement creates an
SQL statement that will be executed at a
later time.
• The parameters to the
PreparedStatement are specified
with set method calls before executing the
PreparedStatement.