- Shopping Bag ( 0 items )
Web applications are an important part of the Java 2 Enterprise Edition (J2EE) platform
because the Web components are responsible for key client-facing presentation and
business logic. Apoorly designed Web application will ruin the best business-tier components
and services. In this chapter, we will review key Web application concepts and
technologies and their use in WebLogic Server, and we will provide a number of recommendations
and best practices related to Web application design and construction
in WebLogic Server.
This chapter also provides the foundation for the discussion of recommended Web
application architectures in Chapter 2 and the construction and deployment of a complex,
realistic Web application in Chapters 3, 4, and 5.
Java Servlets and JSP Key Concepts
In this section we willreview some key concepts related to Java Servlets and
JavaServer Pages. If you are unfamiliar with these technologies, or if you need additional
background material, you should read one of the many fine books available on
the subject. Suggestions include Java Servlet Programming Bible by Suresh Rajagopalan
et. al. (John Wiley & Sons, 2002), Java Servlet Programming by Jason Hunter (O'Reilly &
Associates, 2001), and Core Servlets and JavaServer Pages by Marty Hall (Prentice Hall
Characteristics of Servlets
Java servlets are fundamental J2EE platform components that provide a
request/response interface for both Web requests and other requests such as XML
messages or file transfer functions. In this section, we will review the characteristics of
Java servlets as background for a comparison of servlets with JavaServer Pages (JSP)
technology and the presentation of best practices later in the chapter.
Servlets Use the Request/Response Model
Java servlets are a request/response mechanism: a programming construct designed to
respond to a particular request with a dynamic response generated by the servlet's specific
Java implementation. Servlets may be used for many types of request/response
scenarios, but they are most often employed in the creation of HyperText Transfer Protocol
(HTTP) responses in a Web application. In this role, servlets replace other HTTP
request/response mechanisms such as Common Gateway Interface (CGI) scripts.
The simple request/response model becomes a little more complex once you add
chaining and filtering capabilities to the servlet specification. Servlets may now participate
in the overall request/response scenario in additional ways, either by preprocessing
the request and passing it on to another servlet to create the response or by
postprocessing the response before returning it to the client. Later in this chapter, we'll
discuss servlet filtering as a mechanism for adding auditing, logging, and debugging
logic to your Web application.
Servlets Are Pure Java Classes
Simply stated, a Java servlet is a pure Java class that implements the javax.servlet
.Servlet interface. The application server creates an instance of the servlet class and
uses it to handle incoming requests. The Servlet interface defines the set of methods
that should be implemented to allow the application server to manage the servlet life
cycle (discussed later in this chapter) and pass requests to the servlet instance for pro-cessing.
Servlets intended for use as HTTP request/response mechanisms normally
extend the javax.servlet.http.HttpServlet class, although they may imple-ment
and use the Servlet interface methods if desired. The HttpServlet class
implements the Servlet interface and implements the init(), destroy(), and
service()methods in a default manner. For example, the service()method in
HttpServlet interrogates the incoming HttpServletRequest object and forwards
the request to a series of individual methods defined in the HttpServlet class
based on the type of request. These methods include the following:
_ doGet()for handling GET , conditional GET , and HEAD requests
_ doPost()for POST requests
_ doPut()for PUT requests
_ doDelete()for DELETE requests
_ doOptions()for OPTIONS requests
_ doTrace()for TRACE requests
The doGet(), doPost(), doPut(), and doDelete()methods in HttpServlet
return a BAD_REQUEST (400) error as their default response. Servlets that extend
HttpServlet typically override and implement one or more of these methods to generate
the desired response. The doOptions()and doTrace()methods are typically
not overridden in the servlet. Their implementations in the HttpServlet class are
designed to generate the proper response, and they are usually sufficient.
A minimal HTTP servlet capable of responding to a GET request requires nothing
more than extending the HttpServlet class and implementing the doGet()
WebLogic Server provides a number of useful sample servlets showing the basic
approach for creating HTTP servlets. These sample servlets are located in the
samples/server/examples/src/examples/servlets subdirectory beneath
the Web-Logic Server home directory, a directory we refer to as $WL_HOME throughout
the rest of the book. We will examine some additional example servlets in detail
during the course of this chapter. These example servlets are available on the companion
Web site for this book at wiley.com/compbooks/masteringweblogic.
Creating the HTML output within the servlet's service()or do XXX )method is
very tedious. This deficiency was addressed in the J2EE specification by introducing a
scripting technology, JavaServer Pages (JSP), discussed later in this chapter.
Servlets Have a Life Cycle
A servlet is an instance of the servlet class and has a life cycle similar to that of any
other Java object. When the servlet is first required to process a request, the application
server loads the servlet class, creates an instance of the class, initializes the instance,
calls the servlet's init()method, and calls the service()method to process the
request. In normal servlet operation, this same instance of the servlet class will be used
for all subsequent requests.
Servlets may be preloaded during WebLogic Server startup by including the An existing servlet instance is destroyed when the application server shuts down or Servlets are normally configured to allow multiple requests to be processed simultaneously BEST PRACTICE Servlets that allow multiple parallel requests must be ... This simple change informs the application server that it may not process multiple WebLogic Server satisfies the single-threaded requirement by creating a small pool You can configure the size of the pool at the Web application level using the Although instance variables are safe to use in single-threaded servlets, class-level BEST PRACTICE In general, you should avoid using single-threaded The HttpServletRequest parameter passed in to the service()or do XXX ) This is not an exhaustive list of the methods available on the HttpServletRequest A useful servlet packaged with the WebLogic Server examples, SnoopServlet , ... Enumeration e = req.getParameterNames(); This servlet can be very useful for debugging HTML forms during development. BEST PRACTICE Use the SnoopServlet as an action target during A servlet is a request/response mechanism that treats each incoming request as an _ Cookies may be set in previous requests and passed back to the server on subsequent _ URL-rewriting may be used to encode small amounts of context information on _ Hidden form fields containing context information may be included in forms. These techniques all have limitations, and none provides the robust data types and JSESSIONID=SESSION_ID!PRIMARY_JVMID_HASH!SECONDARY_JVM_HASH!CREATION_TIME WebLogic Server uses exclamation marks to separate portions of the session ID. The
element in the web.xml file for the Web application. You can also provide
initialization parameters in this file using
Server will preload and call init()on the servlet during startup, passing the specified
initialization parameters to the init()method in the ServletConfig object.
intends to reload the servlet class and create a new instance. The server calls the
destroy()method on the servlet prior to removing the servlet instance and unloading
the class. This allows the servlet to clean up any resources it may have opened during
initialization or operation.
Servlets Allow Multiple Parallel Requests
by a single servlet instance. In other words, the servlet's methods must be
thread-safe. You must take care to avoid using class- or instance-level variables unless
access is made thread-safe through synchronization logic. Typically, all variables and
objects required to process the request are created within the service()or do XXX )
method itself, making them local to the specific thread and request being processed.
thread-safe. Do not share class- or instance-level variables unless
synchronization logic provides thread safety.
Servlets may be configured to disallow multiple parallel requests by defining the
servlet class as implementing the SingleThreadModel interface:
public class TrivialSingleThreadServlet
extends HttpServlet implements SingleThreadModel
public void init(ServletConfig config)throws ServletException
requests through the same servlet instance simultaneously. The application server can
honor this restriction in multiple ways: It may block and queue up requests for processing
through a single instance, or it may create multiple servlet instances as needed
to fulfill parallel requests. The servlet specification does not dictate how application
servers should avoid parallel processing in the same instance.
of servlet instances (the default pool size is five) that are used to process multiple
requests. In older versions of WebLogic Server, multiple parallel requests in excess of
the pool size would block waiting for the first available servlet instance. This behavior
changed in WebLogic Server 7.0. The server now creates, initializes, and discards a new
instance of the servlet for each request rather than blocking an execute thread under
these conditions. Set the pool size properly to avoid this extra servlet creation and initialization
single-threaded-servlet-pool-size element in the weblogic.xml deployment
descriptor. If you choose to employ single-threaded servlets in high-volume
applications, consider increasing the pool size to a level comparable to the number of
execute threads in the server to eliminate the potential overhead required to create
extra servlet instances on the fly to process requests.
static variables are shared between these instances, so access to this type of static data
must be thread-safe even when using the SingleThreadModel technique. Deploying
and executing this TrivialSingleThreadServlet example verifies this pooling
behavior in WebLogic Server. The first servlet request causes WebLogic Server to
create five instances of the servlet, as evidenced by five separate invocations of the
init()method and the subsequent writing of five "Here!" messages in the log.
servlets. If you find that you need to use servlets that implement the
SingleThreadModel, use the single-threaded-servlet-pool-size element
to set the pool size properly to avoid the overhead of creating and initializing
extra servlet instances to handle peaks in the number of concurrent requests to
Servlets May Access Request Data
method contains a wealth of information available to the servlet during the processing
of the request. Useful data in the HttpServletRequest is summarized in Table 1.1.
class or its superclass, ServletRequest . Refer to the servlet javadocs at
java.sun.com/products/servlet/2.3/javadoc/index.html or a good reference
book on servlets for a complete list including parameter types, return types, and other
illustrates the use of many of the methods available on the HttpServletRequest
object. For example, this section of SnoopServlet illustrates how to retrieve and display
the names and values of all parameters passed to the servlet:
Servlet parameters (Single Value style):");
String name =(String)e.nextElement();
out.println(" " ++name +" ==" ++req.getParameter(name));
Specify SnoopServlet as the action for an HTML form to view all of the parameters,
cookies, and headers sent by the browser during submission of the form. Nothing is
more frustrating than spending time debugging a servlet only to find that the HTML
form had an improperly named input item.
development and debugging to inspect request information and verify HTML
Note that SnoopFilter, a servlet filter discussed later in this chapter, provides a
superior mechanism for viewing request information for some or all pages in the Web
Servlets Use Session Tracking
independent processing event with no relationship to past or future requests. In other
words, the processing is stateless. The HTTP protocol is also a stateless protocol: Each
request from the Web browser is independent of previous or subsequent requests.
Linking current requests to previous requests from the same client requires a mechanism
for preserving context or state information from request to request. There are a
number of HTML-based techniques for preserving context or state information:
every hyperlink on the generated page.
flexibility needed to implement true state management. Fortunately, the session tracking
capability defined in the J2EE servlet model provides an excellent solution.
Session tracking provides a flexible hash-table-like structure called an HttpSession
that can be used to store any serializable Java object and make it available in subsequent
requests. To identify the specific client making the request and look up its
session information, session tracking uses a cookie or URL-encoded session ID passed
to the server on subsequent requests. In WebLogic Server, this session ID has the name
JSESSIONID by default and consists of a long hash identifying the client plus
creation-time and cluster information. The format of the session ID is
first portion is used by the session tracking implementation in WebLogic Server to look
up the client's HttpSession object in the Web application context.
Excerpted from Mastering BEA WebLogic Server
by Gregory Nyberg Robert Patrick Paul Bauerschmidt Jeff McDaniel Raja Mukherjee
Copyright © 2003 by Gregory Nyberg, Robert Patrick, Paul Bauerschmidt, Jeff McDaniel, Raja Mukherjee.
Excerpted by permission.
All rights reserved. No part of this excerpt may be reproduced or reprinted without permission in writing from the publisher.
Excerpts are provided by Dial-A-Book Inc. solely for the personal use of visitors to this web site.
An existing servlet instance is destroyed when the application server shuts down or
Servlets are normally configured to allow multiple requests to be processed simultaneously
BEST PRACTICE Servlets that allow multiple parallel requests must be
This simple change informs the application server that it may not process multiple
WebLogic Server satisfies the single-threaded requirement by creating a small pool
You can configure the size of the pool at the Web application level using the
Although instance variables are safe to use in single-threaded servlets, class-level
BEST PRACTICE In general, you should avoid using single-threaded
The HttpServletRequest parameter passed in to the service()or do XXX )
This is not an exhaustive list of the methods available on the HttpServletRequest
A useful servlet packaged with the WebLogic Server examples, SnoopServlet ,
Enumeration e = req.getParameterNames();
This servlet can be very useful for debugging HTML forms during development.
BEST PRACTICE Use the SnoopServlet as an action target during
A servlet is a request/response mechanism that treats each incoming request as an
_ Cookies may be set in previous requests and passed back to the server on subsequent
_ URL-rewriting may be used to encode small amounts of context information on
_ Hidden form fields containing context information may be included in forms.
These techniques all have limitations, and none provides the robust data types and
WebLogic Server uses exclamation marks to separate portions of the session ID. The
About the Authors.
Chapter 1. Building Web Applications in WebLogic.
Chapter 2. Choosing a Web Application Architecture.
Chapter 3. Designing an Example J2EE Application.
Chapter 4. Building an Example Web Application.
Chapter 5. Packaging and Deploying WebLogic Web Applications.
Chapter 6. Building Enterprise JavaBeans in WebLogic Server.
Chapter 7. Building an Example EJB Application.
Chapter 8. Packaging and Deploying WebLogic EJB Applications.
Chapter 9. Using WebLogic JMS.
Chapter 10. Using WebLogic Security.
Chapter 11. Administering and Deploying Applications In WebLogic Server.
Chapter 12. Optimizing WebLogic Server Performance.
Chapter 13. Development Environment Best Practices.
Chapter 14. Production Environment Best Practices.
Chapter 15. Developing and Deploying Web Services.