You are on page 1of 21

Init parameters :

1. Accessed by servlet
i. servlet init parameters(inside <servlet> in DD)
ii. Accessed via ServletConfig
out.println(getServletConfig().getInitParameter());
<web-app>
<servlet>
<servlet-name></servlet-name>
<servlet-class></servlet-class>
<init-param>
<param-name></param-name>
<param-value></param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name></servlet-name>
<url-pattern></url-pattern>
</servlet-mapping>
</web-app>

1. u cant access init parameters unless the servlet is initialized i.e not iside
constructor.
2. The container reads the init parameters from the DD and gives them to
ServletConfig and passes ServletConfig to servlet init method.
3.init parameters r read once when container creates a servlet.
4.so if u want to change them u have to redeploy.

5. hot deploy comes to rescur.if u simply redeploy all apps go down which is bad on
production so better option is hot redeploy which redeploys only one particular
app.Its there on tomcat also.
6.In the real world even hot deploy can take a lot of time.

How can a JSP get servlet init parameters


i.Use request attribute
pass the model info to the jsp in a request attribute using request dispatcher.
Disadvantage:
this way info is available only to jsp to which you forwarded the request using
RequestDispatcher
ii. read all init parameters and store them at common place
one servlet read all init parameters and store them at common place(request)
where all others can use
Disadvantage:
We have to know at which servlet would run first when the app is deployed and any
change to the web-app could break the whole thing
iii.Configure the dd for all the servlets
configure the init parameters for all the servlets in the dd.
Disadvantage:
Not maintainable
2.Accessed by JSP and other parts of application

i.context init parameters(inside <web-app> in DD)


ii.accessed via ServletContext
<web-app>
<servlet>
<servlet-name></servlet-name>
<servlet-class></servlet-class>
</servlet>
<context-param>
<param-name></param-name>
<param-value></param-value>
</context-param>
</web-app>
iii.Available to other parts of application

How and when are ServletConfig and ServletContext created????


Init Parameters are read only once when the container initializes the servlet

i.container reads dd including init parameters and creates ServletConfig


ii.creates name-value pair of Strings for each init parameter
iii.Container gives the references of name-value pairs to ServletConfig
iv.creates a new instance of servlet class
v.calls the init() method passing the reference to ServletConfig

Similarly ServletContext is created except that the name value pairs are created
first and then the ServletContext is created.Servlet Context is created when the web
app is deployed.
--------------------------------------------------------------------init();
init(ServletConfig servletconfig);(calls the no-arg version)

you would never need to override init(ServletConfig servletconfig);

How many ServletConfig and ServletContext objects?

One servletContext per web-app and one ServletConfig per servlet or JSP
If the app is distributed there is one ServletContext per JVM

What is the main use of <context-param>???????

For storing info used by complete app like database look up names

Different ways of getting ServletContext

The ServletContext object is contained within the ServletConfig object,


which the Web server provides the servlet when the servlet is
initialized(source : sun)
getServletConfig().getServletContext().getInitParameter();

this.getServletContext().getInitParameter();

The above are used in following situations


i.when your servlet does not extend from HttpServlet or GenericServlet coz
getServletContext() comes from GeericServlet class
ii. when you are in a utility class to which someone might have passed ServletConfig
and if it wants to access ServletContext.

Remember theres no setInitParameter(); they are only set in dd.

What else u can do with ServletContext

So for simple experiments you do logging using the log(String) method.

What if you want an app init parameter thats


a database DataSource.
1. Now you cant stuff objects into xml init parameters,all that is there is strings
2. Listeners :
a. Listen to events (which I this case is context initialization events) and
do the work ( which in this case is create a datasource).
3. ServletContextListener :
a. Create a class that implements javax.servlet.ServletContextListener

b. Gets notified for 2 events


i. When context is initialized : app is deployed
ii. When context is destroyed : app is undeployed or goes down
c. When initialized
i. Get parameter from context
ii. Make connection using name
iii. Store connection as an attribute.
d. When destroyed
i. Close the connection

Where do I put the class?


Who instantiates it?
How do I register for the events?
How does the listener set the attribute in the
right Context?
WEB-INF
Container
By putting the <listener> in the dd
<listener>
<listener-class>com.example.MyServletListener</listener-class>
</listener>

Q. Do Servlet attributes have to be


serializable?
Not really only session attributes and that too if the app is distributed.

The getAttribute(); returns a Object so need to cast it accordingly


But getInitParameter(); returns a String.

8 kinds of listeners :
1. When theres a lifecycle moment theres a listener to hear about it

2. You can listen for events related to :

a. Context events
b. Context attributes
c. Servlet requests

d. Servlet request attributes


e. HTTP session
f.

HTTP session attributes

3. Scenario Listener Interface Event Type

Why HttpSessionBindingListener

When the objects of the class want to know when they are added they
implement this interface.
This is useful e.g if customer data has changed and added to session so the
latest data has to be displayed and updated from the listener.
Entity beans implement this interface.

Remembering Listeners

What exactly is an attribute?


1. Its an object set(referred to as bound) into one of the three other servlet API
objects :
HttpServletRequest(request),Servletcontext(context),HttpSession(session).

2. Think of it as a name value pair(String,Object) in a map instance variable.

Scope of Attributes :
1. Who can see it and how long does it live.
2. Attributes are not Parameters

Attribute Scope

The Attribute API is same for all three


attribute scopes :
1. Object getAttribute(String name)
2. setAttribute(String name,Object value)
3. removeAttribute(String name)

4. enumeration getAttributeNames()

Attribute Scope and Thread Safety


1. Context scope isnt thread safe. Coz multiple threads
2. Session scope isnt either.Coz multiple browser windows
3. Syncronising service() method is spectacularly bad coz it kills concurrency .
4. It protects against other threads from the same servlet but it wont protect
against completely different servlet or JSP.
5.

synchronize the code that accesses context and session.


Eg.

HttpSession session = request.getSession();


synchronized(session){

Acquiring lock on context for thread safety


1. If everyone accessing the context attributes has to get a lock on context than
at any given time only one thread can be setting and getting the attributes.

Acquiring lock on HttpSession for thread


safety
1. Httpsession are not thread safe as the client(browser) can make multiple
requests using the same session but different browser windows.

2. Synchronising adds expense in checking , acquiring and releasing locks.

How to protect instance variables?


1. Implement the interface SingleThreadModel(STM) .
2. It has no methods
3. Ensures that no 2 methods access a servlets service() method
simultaneously.

How does a web container guarantee a


servlet gets one request at a time?
1. The web container vendor has a choice
i.

One servlet instance and a queue :


The container creates one servlet instance and queues requests
and process one request completely before allowing the next to
proceed

ii.

Create a pool of servlet instances.


Create a pool of servlet instances and process requests
concurrently.

iii.

The second approach can create problem. Eg if one of the instance


variables is used to record the number of requests processed.

Q . are instance variables thread safe?


No.
Q. but they wud be if u use STM?
Right but thats very stupid.
Q. but if u synchronize service() method then ivs wud be thread safe?
Ya but thats the same as STM.
Q. So how then u make IVs thread safe?
You dont need to. A well written servlet will not have any IVs and if they do they
are final.
But even final IVs can be manipulated unless they are immutable.
Q. So what do u do if u want multiple threads share something?
It can be done in 2 ways :
1. Use some LV in service method
2. Put the value in some attribute in most appropriate scope.

Request Dispatcher Revealed


1. Helps in another part of the component take over the request
2. Have 2 methods forward() and include()
3. Both take the request and response , which the component u r forwarding
to will need to finish the job.
4. Forward() is by far the most popular, behind the scenes include method is
used by JSPs in the <jsp:include>
5. U can get the dispatcher from either the request or the context.
6. RequestDispatcher view = request.getRequestDispatcher(result.jsp);
a. The method takes a String path

b. If no forward slash then container looks for result.jsp in the same


logical location the request is in.
c. But u cant fool the container in going outside the ROOT using
something like
../../../
7. You have to specify path from root when trying to get dispatcher from
context
RequestDispatcher view =
getServletContext().getRequestDispatcher(/result.jsp);
8. include method is a temporary hand-off , it asks for help from other
component but comes back
Which out of the following are thread safe?

A piece of code is thread-safe if it functions correctly during simultaneous


execution by multiple threads

i.context scoped attributes


ii.session scoped attributes
iii.request-scoped attributes
iv.local variables in service methods
v.static variables in the servlet
vi.instance variables in the servlet

Only local and request

Ref : http://www.jguru.com/faq/view.jsp?EID=150

This is actually a very complex issue. A few guidelines:


1. The init() method is guaranteed to be called once per servlet instance, when the
servlet is loaded. You don't have to worry about thread safety inside this method,
since it is only called by a single thread, and the web server will wait until that
thread exits before sending any more threads into your service() method.
2. Every new client request generates (or allocates) a new thread; that thread calls the
service() method of your servlet (which may in turn call doPost(), doGet() and so
forth).
3. Under most circumstances, there is only one instance of your servlet, no matter how
many client requests are in process. That means that at any given moment, there
may be many threads running inside the service() method of your solo instance, all
sharing the same instance data and potentially stepping on each other's toes. This
means that you should be careful to synchronize access to shared data (instance
variables) using the synchronized keyword.
4. If you absolutely can't deal with synchronizing, you can declare that your servlet
&amp;quot;implements SingleThreadModel&amp;quot;. This empty interface tells
the web server to only send one client request at a time into your servlet. From the
JavaDoc: &amp;quot;If the target servlet is flagged with this interface, the

servlet programmer is guaranteed that no two threads will execute


concurrently the service method of that servlet. This guarantee is ensured by
maintaining a pool of servlet instances for each such servlet, and dispatching each
service call to a free servlet. In essence, if the servlet implements this interface, the
servlet will be thread safe.&amp;quot; Note that this is not an ideal solution, since
performance may suffer (depending on the size of the instance pool), plus it's more
difficult to share data across instances than within a single instance.

You might also like