Servlet basics lecture

Download Report

Transcript Servlet basics lecture

Object-Oriented Enterprise
Application Development
Introduction to Servlets
Topics
During this class we will examine:
Motivation
Require packages
Classes
Lifecycle
Web Applications
Development Approaches
In the past few years, many alternative
technologies have been presented for web
application development:
CGI
Proprietary APIs
Server-Side JavaScript
Microsoft ASPs
Java Servlets
CGI
(1 of 2)
In a CGI application, each client request
executes a program on the server.
These are typically written in C, C++ or Perl.
Could be embedded within a web server and
thus didn't require any new software.
CGI
(2 of 2)
While this satisfies the requirement for
dynamic content, there are potential
problems:
Starting a new process is expensive
Poorly written code is a significant security
hazard.
Difficult to communicate between the CGI
program and the client.
Proprietary APIs
Many vendors offered proprietary APIs:
Netscape:
Microsoft:
O'Reilly:
NSAPI
ISAPI
WSAPI
Since they're proprietary, you're binding
your architecture to a particular vendor.
Server-Side JavaScript
This is JavaScript that's placed into
precompiled HTML pages and then
executed on the server.
Improved performance.
Improved security.
Only a few products actually support this
technique.
Microsoft ASP
This is similar to server-side JavaScript, but
the code isn't precompiled.
This technique is tied to the Microsoft IIS
application server or other products where
it's an add-on module.
Enterprise Java
As opposed to investing in proprietary
techniques, many vendors have started
backing the use of enterprise Java.
Java has a well-defined API.
Java has been widely accepted by the industry
for its portability.
This will be the focus of this course.
Servlet Background
Servlets Defined
Java servlets are precompiled Java
programs that are executed on a server.
Servlets are installed in a web container
that is responsible for locating, loading, and
executing the servlet when an appropriate
request is issued.
Essential Benefits
Because they're written in Java and
executed on the server, servlets provide:
Efficiency
Persistence
Portability
Robustness
Extensibility
Security
Efficiency
(1 of 2)
Servlets are loaded and initialized only
once: when the servlet engine receives the
first request for that servlet.
Servlet engines automatically multi-thread
each servlet.
There is only a single instance of any given
servlet in memory. Each request for that servlet
is a new thread that shares the servlet instance.
Efficiency
(2 of 2)
Many web servers
load balance servlet
requests across
multiple physical
servers to improve
performance.
This results in better
performance and fault
tolerance.
Persistence
(1 of 2)
Servlets can hold data that spans across the
various requests received by various clients.
This can improve performance by treating
each servlet as a singleton.
This persistent data is lost if the servlet
engine unloads the servlet class from
memory.
Persistence
(2 of 2)
This persistence mechanism doesn't provide
session persistence for each client.
This means that applications built on the
familiar "shopping cart" metaphor must
use a different approach to persist the data
for a specific user of that application.
We'll address this technique during the next
lecture.
Portability
Because the servlets are written in pure
Java, they can be moved into any
environment that supports servlets.
Always make sure you confirm the version
of the JDK that you used to write your
servlets as well as the version of the servlet
specification.
Robustness
Because servlets are written in Java, they
have access to the entire JDK.
This includes all inherent Java capabilities
such as inheritance, polymorphism, and
exception handling.
Extensibility
Like all other classes, we can design
servlets that are base classes that provide
basic functionality.
We can then inherit from these base servlets
to provide additional functionality.
This allows the use of relevant design
patterns such as template method or
command.
Security
Because servlets are executed on the server,
the client never gains access to the code.
Servlets can also take advantage of the
security manager and cryptography classes.
There is also code security; a servlet that
terminates abnormally usually won't crash
the servlet engine.
Servlet Lifecycle
Servlet Lifecycle
(1 of 4)
All servlets follow the same lifecycle.
The init() method is called when the servlet
class is first loaded by the servlet engine.
The service() method is called each time
the servlet is requested by a client.
The destroy() method is called just before
the servlet engine unloads the servlet class from
memory.
Servlet Lifecycle
(2 of 4)
The init() method is where a servlet's
life begins.
This method is only called when the servlet
class is loaded by the servlet engine.
If you override this method be sure to call the
parent class' init() method.
This makes the init() method useful for
doing one-time servlet configuration.
Servlet Lifecycle
(3 of 4)
The service() method is where a servlet
spends most of its life.
This method is invoked one (1) time for
each client request made to the servlet.
This method typically acts as a dispatcher
by interrogating the client's request and
acting on the data it finds there.
Servlet Lifecycle
(4 of 4)
The destroy() method is where a
servlet's life ends.
This method is only called when the servlet
class is unloaded by the servlet engine.
If you override this method be sure to call the
parent class' destroy() method.
This makes the destroy() method useful
for doing one-time servlet cleanup.
Servlets & Java
Required Packages
(1 of 2)
Servlets are included in J2EE or in the
J2SDK as an additional download.
The are two (2) packages required for
servlets:
javax.servlet.*
javax.servlet.http.*
Required Packages
(2 of 2)
The javax.servlet package provides
the basic interfaces that must be
implemented and extended by all servlets.
The javax.servlet.http package
provides the key classes used to construct
servlet-based applications using the HTTP
protocol.
Servlets
At the heart of each servlet is the Servlet
interface containing the following methods:
destroy
getServletConfig
getServletInfo
init
service
Generic Servlets
For non-HTTP based servlets, we inherit
from the GenericServlet class.
GenericServlets provide default
implementations for the init() and
destroy() methods. However, servlets
inherited from this class must implement
the service() method.
Generic Requests
When a request is issued to the servlet, we
must be able to process that request.
This may require the parsing of arguments or
other complex actions specific to our
implementation.
In the generic case this means that we need
to construct a class that implements the
ServletRequest interface.
Generic Responses
Once the servlet has completed its work, it
needs to send any results back to the client
who made the original request.
In the generic case this means that we need
to construct a class that implements the
ServletResponse interface.
Generic Dispatchers
Sometimes we may want to delegate a
request made to one servlet to an entirely
different servlet.
This is accomplished using a class that
implements the RequestDispatcher
interface.
HTTP Servlets
For HTTP based servlets, we inherit from
the HttpServlet class.
This class provides a default service()
method that we won't usually override.
This method knows how to parse requests made
using the HTTP protocol.
Sample Code – HelloWorld
(1 of 2)
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4. public class HelloWorld
extends HttpServlet {
5.
public void
doGet(HttpServletRequest rqst,
HttpServletResponse resp)
throws IOException, ServletException {
6.
resp.setContentType("text/html");
7.
PrintWriter out = new PrintWriter(
resp.getOutputStream() );
Sample Code – HelloWorld
(2 of 2)
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
}
20. }
out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>");
out.println("HelloWorld");
out.println("</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");
out.println("<P>Hello, World!</P>");
out.println("</BODY>");
out.println("</HTML>");
out.close();
HTTP Servlet Anatomy
(1 of 2)
The HelloWorld servlet illustrates some
of the key servlet elements.
The servlet extends the HttpServlet class.
The doGet() method accepts two (2)
arguments and throws two (2) exceptions.
HTTP Servlet Anatomy
(2 of 2)
But how is doGet() invoked?
The answer lies in the default
implementation of the service() method
within the HttpServlet class.
When a GET request is received, the
service() method automatically invokes
the doGet() method.
Initialization Parameters
Justification
Sometimes we want to initialize a servlet
when it's first loaded by the servlet engine.
For instance, we might want to load some
configuration settings before allowing
processing to continue.
This can be useful for testing when you
don't want to configure a web page to
initiate the test.
Technique
We can embed such values in the
application's web.xml file.
We access these values within the servlet's
init() method when it is first loaded.
To access these initialization parameters
we use the getInitParameter()
method on the ServletConfig reference
passed to the init() method.
Sample Code – Message
(1 of 2)
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Message
extends HttpServlet {
private String msg = null;
public void init( ServletConfig cfg )
throws ServletException {
super.init( cfg );
msg = cfg.getInitParameter("msg");
if ( msg == null) {
msg = "no.message.specified";
}
}
Sample Code – Message
(2 of 2)
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
}
23. }
resp.setContentType("text/html");
PrintWriter out = new PrintWriter(
resp.getOutputStream() );
out.println("<HTML><HEAD><TITLE>");
out.println("Message");
out.println("</TITLE></HEAD>");
out.println("<BODY>");
out.println("<P>" + msg + "</P>");
out.println("</BODY></HTML>");
out.close();
Servlet Pitfalls
Local Data Members
(1 of 3)
In the Message servlet, I declared a local
data member called msg.
With regular classes, this data member
would be specific to each object.
For servlets, this data member is shared
across all requests made to the Message
servlet.
Local Data Members
(2 of 3)
This means that we can't use local data
members to store user- or session-specific
data.
Each new access to that data may result in the
value being changed. This change will affect all
users of that servlet.
However, such data members are useful if
the value in question is meant to be a
constant.
Local Data Members
(3 of 3)
To pass the various data members between
methods within the servlet, we are forced to
adopt the approach of using an aggregate
class.
This could be something as simple as using a
Java Collection class.
We could also devise our own custom class.
Review
During this class we have discussed:
Motivation
Require packages
Classes
Lifecycle
Resources
Developing Java Servlets
James Goodwill, Sam's Publishing, 1999.
ISBN: 0-672-31600-5
Core Servlets and JavaServer Pages
Marty Hall, Prentice-Hall, Inc., 2000.
ISBN: 0-13-089340-4
Java 2 Platform, Enterprise Edition
B. Shannon, et al., Addison-Wesley, 2000.
ISBN: 0-201-70456-0
Coming Attractions
Next week we'll look at servlets in greater
depth including how to invoke them from
an HTML page and how to implement the
"shopping cart" metaphor.
Please read Chapters 3 & 9 in your text.