Question

Is it a good practice for a class to extend HttpServlet and implement ServletContextListener?

public Myclass extends HttpServlet implements ServletcontextListener {
}

What are the pros and cons of doing this?

Was it helpful?

Solution

Some thoughts:

  • You will have at least two instances of your class. The container create one as ServletContextListener and at least one as HttpServlet when your servlet get an incoming request.
  • Since the 2+ instances you cannot use instance (just static) members to share data.
  • It's easier if other classes don't use the data/objects that you initialize and share in the listener because you don't have to put these data/objects to the application scope in the ServletContextListener and retrieve them in the HttpServlet.
  • If your initialization logic is complex maybe it's worth to separate it from the servlet code (e.g. putting the initialization code to a different class and using the application scope to get the shared objects in the servlet).

OTHER TIPS

It all depends on you, the implementer. ServletcontextListener has its particular purpose. Make sure you know what it is for before using it.

In case you are creating an HTTP servlet you must extend HttpServlet.If your class wants to "receive notifications about changes to the servlet context of the web application" (copied from javadocs) it is part of, you have to implement ServletcontextListener.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top