Is it a good practice for a class to extend HttpServlet
and implement ServletContextListener
?
public Myclass extends HttpServlet implements S开发者_运维问答ervletcontextListener {
}
What are the pros and cons of doing this?
Some thoughts:
- You will have at least two instances of your class. The container create one as
ServletContextListener
and at least one asHttpServlet
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 theHttpServlet
. - 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).
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.
精彩评论