• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Registering Listeners in web.xml

 
Paul Statham
Ranch Hand
Posts: 60
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Saloon Keeper
Pie
Posts: 2536
113
Android Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 113
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic