Sunday, February 3, 2013

Head First Servlets and JSP: Chapter 5 Attributes & Listners

Servlet Config
in order not to hard code some values, you can add these values in web.xml like this

later, we can read these values using

The container reads this information once, you need hotdeploy if you want to change these values

Servlet config is available only for the mentioned servlets, (e.g. BeerParamTests in the previous example), in order to make something global you should define context param, context param are available for the whole website 

now you can read this value wherever you want

So, we have one servletConfig object for each servlet (including jsp as a jsp page is converted to servlet) and one servletContext for the whole app.

the idea of listeners is like interceptors, when something happens go and call them.
we have different type of listeners

1- ServletContextListener: this listener is used if you want to be notified if a context param is created or destroyed.

example of using this listener: unfortunately, in context param you can add only string values, you cannot add objects, so you can use the Listener to be triggered when a new context param is added and then add the object as attribute:

the listener should be defined in web.xml

list of listeners

Attributes Scopes

Context Attributes are not thread safe, so you need to synchronize them if you want

Session Attributes also not thread safe:

Request Attribute are thread safe.

you can define a servlet to implement SingleThreadModel, then the servlet will not receive concurrent requests, the container will send the requests one by one.

No comments:

Post a Comment