문제

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?

도움이 되었습니까?

해결책

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).

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top