Datasheet
Patrick c01.tex V3 - 09/18/2009 12:15pm Page 4
Chapter 1: Building Web Applications in WebLogic
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
<load-on-startup>
element in the
web.xml
file for the web application or by including the
loadOnStartup
attribute
in the
@WLServlet
annotation block in the servlet’s class definition. You can also provide
initialization parameters in the
web.xml
file using
<init-param>
elements or by including them
in the
@WLServlet
annotation block. WebLogic Server will preload and call
init()
on the servlet
during startup, passing the specified initialization parameters to the
init()
method in the
ServletConfig
object.
An existing servlet instance is destroyed when the application server shuts down or 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
Servlets are normally configured to allow multiple requests to be processed simultaneously 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
doXXX()
method itself, making them local to the specific thread and request
being processed.
Best Practice
Servlets that allow multiple parallel requests must be 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
{
super.init(config);
System.out.println("Here!");
}
...
This simple change informs the application server that it may not process multiple requests through
the same servlet instance simultaneously. Although WebLogic Server continues to implement this
mechanism for enforcing single-threaded servlets, the Servlet 2.4 specification has deprecated its
4