Ismail Marmoush
Ismail Marmoush

Reputation: 13600

What are the advantages or use cases of adding a Servlet, or a Filter programmatically?

This Question makes me wonder, cause I don't see programmatically adding a servlet using a contextListener (which runs once as far as I know ) advantages over DD or Annotations. and I wish to know about a common use case where it's helpful adding them programmatically.

If there was a way of adding servlets programmatically in Runtime (during app running ) I could have thought of some cases, but seems it's only done through contextListener or

from the onStartup method of a ServletContainerInitializer implementation.

as Servlet 3.0 states.

Upvotes: 0

Views: 640

Answers (1)

Piotr Kochański
Piotr Kochański

Reputation: 22682

Ability to add servlets etc. during runtime was designed mostly for frameworks creators.

If you create a framework which, say, works with plain POJO Java objects, then you need to create servlets at some point - they have to expose POJO classes for the web access. Because you can create servlets dynamically, there is no need for configuration files for POJO classes. Nice!

The general framework might have also filters that can be dynamically "switch on/off", for instance there could be switchable filter that takes care of user authorization/authentication.

In "normal" applications usually all Servlets, Filters are known upfront, so programatic addition is hardly needed.

Upvotes: 1

Related Questions