Transcript PowerPoint

Servlet details
Russell Beale
Servlet lifecycle


The servlet container creates only one
instance of each servlet
Each use request handled with a
separate thread


So copes with many users
Each thread calls doGet or doPost
methods
Behaviour




init() method called when servlet first
created
Each time server receives request for servlet,
spawns new thread and calls the service
method
This checks the HTTP request type (GET, SET,
etc.) and calls doGet, doPost, etc. as
appropriate
destroy() called when server removes
previously loaded servlets
init()


One-off initialisation code goes here
E.g. connection to database


Save connection in an instance variable
Remember to throw appropriate
exceptions (ServletException)

Do not call System.exit()
Beware!




Since the service() method can be called
by multiple clients, it runs in parallel
Need to be aware of threading issues and
concurrent access
May have to sync access to variables, or
database, or similar
If have database connection opened in
init(), then there’s only one connection may be slow for many users
Sharing information

Web componets usually work with other
objects to do their thing



Share objects that are attributes of a public
scope
Invoke other web resources
Use a database
Scope objects

Four scope objects which allow servlets to
share information

Web Context - javax.servlet.ServletContext


Session - javax.servlet.http.HttpSession


Accessible from web components handling a
request that belongs to the session
Request - javax.servlet.HttpServletRequest


Accessible from web compoents within a web
context
Accessible from web components handling the
request
Page - javax.servlet.jsp.PageContext

Accesible from the java server page that creates
the object
Scope objects


Get attribute values from servlet scope
objects using getAttribute method
Set attributes using setAttribute
method
Invoking other web resources

Indirectly


Embed a URL in the response that points
to another web component
Directly


Invoked whilst executing
Can


include the content of another resource
Forward the request to another source
How?

First, obtain a RequestDispatcher object

Using get RequestDispatcher(“URL”)
Including another resource


E.g. copyright information, adverts
Use include method of
RequestDispatcher


include(request, response)
Sends the request to the included web
component, which executes and returns
the response in the response object
Passing on control



E.g. One servlet does initial processing,
another completes it and generates response
To transfer control, use forward method of
a RequestDispatcher
Request URL is set to path of forwarded page


Original URI and parts are saved as request
attributes
Can’t forward on if already accessed
PrintWriter object (or
ServletOutputStream)

Throws IllegalStateException