0

In Servlets we have ServletConfig and ServletContext. Going through the API i see that both are interfaces. Following are my doubts

1.ServletConfig and ServletContext are interfaces, how are these object created if they are interfaces?

2.Is that the classes of the container implements these interfaces and provide the implementation?

3.Where can i find the instantiation code of ServletConfig and ServletContext?

4.When exactly are the ServletConfig and ServletContext created.

Also i read that there is SerlvetContextListener and it has methods context Created() and contextDestroyed(). And these methods are called when the server is started. Is that how we can come to know that ServletContext object is created ?. Just reading the book is not giving me clear picture about ServletConfig and ServletContext. Want to know the code how these are created.Can someone please explain or provide links so that i can go through and get a clear picture

Avinash Reddy
  • 2,204
  • 3
  • 25
  • 44

1 Answers1

2

1.ServletConfig and ServletContext are interfaces, how are these object created if they are interfaces?

The implementation is provided by the container. See ApplicationContext class used in tomcat

2.Is that the classes of the container implements these interfaces and provide the implementation?

Same as #1

3.Where can i find the instantiation code of ServletConfig and ServletContext?

Search tomcat-core jar in grep code, and you can find the implementations. I linked the ServletContext implementation above.

4.When exactly are the ServletConfig and ServletContext created.

The ServletContext is an application level object and ServletConfig is per Servlet. Both would be created when your application is loaded.

Also i read that there is SerlvetContextListener and it has methods context Created() and contextDestroyed(). And these methods are called when the server is started. Is that how we can come to know that ServletContext object is created ?

Create a sample app and add a ServletContextListener. See example here. You can add logs in the contextInitialized and Destroyed method to see when they get invoked.

6ton
  • 4,174
  • 1
  • 22
  • 37