aspose file tools*
The moose likes Web Component Certification (SCWCD/OCPJWCD) and the fly likes Registering Listeners in web.xml Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Web Component Certification (SCWCD/OCPJWCD)
Bookmark "Registering Listeners in web.xml" Watch "Registering Listeners in web.xml" New topic
Author

Registering Listeners in web.xml

Paul Statham
Ranch Hand

Joined: Dec 05, 2008
Posts: 41
In HFSJ they use an registering an ServletContextListener as their example in web.xml, which is something like this



With the comment that the <listener> element does not go inside the <servlet> element because a context listener is for the context not for a specific servlet. So my question is, what about a ServletRequestListener say? That can be specific to a servlet, in that example would <listener> appear inside <servlet>, or is it always outside <servlet>?
Frits Walraven
Creator of Enthuware JWS+ V6
Bartender

Joined: Apr 07, 2010
Posts: 1678
    
  25

So my question is, what about a ServletRequestListener say? That can be specific to a servlet, in that example would <listener> appear inside <servlet>, or is it always outside <servlet>?

Listeners (i.e. all type of listeners) are always registered outside <servlet>.

Regards,
Frits
Stoian Azarov
Ranch Hand

Joined: Jun 01, 2011
Posts: 113
If you want to create listener that is specific for a servlet you have to use some kind of workaround. As Frist already pointed you cannot declare <listener> inside <servlet> tag.
If your goal is to run the listener for every request that is forwarded to specific listenr you can use filtration code something like this.

Of course, this won't be a smart solution because you are hardcoding the servlet path into the listener code and once the servlet <url-pattern> changes in web.xml the code won't work. And the performance will suffer because this listener will be called for every request in the web application.
Because of that, it might be better in this case to use a filter, that is mapped to the servlet's url pattern. That way you will keep the configuration in the DD and it will be easier to make changes.
Yet another possibility is to put your code into servlet's init() method(if the code should be executed only once when servlet is initialized) or in service() or one of the doXXX() methods. Keep in mind that if you override service() method you've better call the overriden version with super.service()

HTH
 
Don't get me started about those stupid light bulbs.
 
subject: Registering Listeners in web.xml