Java Reference
In-Depth Information
Extensibility
Another advantage servlets gain by being developed in an object-oriented language such as
Java is that they can be extended and polymorphed into new objects that better suit your needs.
A good example of this is an online catalog. You might want to display the same catalog search
tool at the top of every dynamic page throughout your Web site. You definitely don't want to
add this code to every one of your servlets. So, you implement a base servlet that builds and
initializes the search tool and then extend it to display transaction-specific responses.
Security
Servlets run on the server side, inheriting the security provided by the Web server. Servlets can
also take advantage of the Java Security Manager.
The Java Servlet Architecture
Two packages make up the servlet architecture:
javax.servlet
and
javax.servlet.http
. The
javax.servlet
package contains the generic interfaces and classes that are implemented and
extended by all servlets. The
java.servlet.http
package contains the classes that are
extended when creating HTTP-specific servlets. An example of this is a simple servlet that
responds using HTML.
At the heart of this architecture is the interface
javax.servlet.Servlet
. It provides the frame-
work for all servlets. The
Servlet
interface defines five methods. The three most important are
the
init()
method, which initializes a servlet; the
service()
method, which receives and
responds to client requests; and the
destroy()
method, which performs cleanup. All servlets
must implement this interface, either directly or through inheritance. It is a very clean object-
oriented approach that makes the interface easy to extend. Figure 2.3 shows an object model
that gives a high-level view of the servlet framework.
GenericServlet
and
HttpServlet
The two main classes are the
GenericServlet
and
HttpServlet
classes. The
HttpServlet
class is extended from
GenericServlet
. When you are developing your own servlets, you will
most likely be extending one of these two classes. Java servlets do not have a
main()
method,
which is why all servlets must implement the
javax.servlet.Servlet
interface. Every time a
server receives a request that points to a servlet it calls that servlet's
service()
method.
If you decide to extend the
GenericServlet
class, you must implement the
service()
method.
The
GenericServlet.service()
method has been defined as an abstract method to force you
to follow this framework. The
service()
method prototype is defined as follows:
public abstract void service(ServletRequest req,
ServletResponse res) throws ServletException, IOException;s