Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

init(ServletConfig config) query

 
Abhay Agarwal
Ranch Hand
Posts: 1376
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

I tried to run a sample servlet code wherein i have not called super.init(config) from within init(ServletConfig config) [overrided in my servlet code] and sample servlet (in Tomcat container) ran fine.



So i want to understand
a.When we override init(ServletConfig config) method in our servlet then is it mandatory to call super.init(config) from within it ?
b. If it is mandatory then why my sample servlet ran fine (without giving any error) ?
c. What are the implications of
i. calling super.init(config) from within init(ServletConfig config) method in our servlet
ii. not calling super.init(config) from within init(ServletConfig config) method in our servlet


Waiting for a reply
 
Shwetha Sharma
Ranch Hand
Posts: 34
Eclipse IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
a.When we override init(ServletConfig config) method in our servlet then is it mandatory to call super.init(config) from within it ?

No it is not mandatory but the servlet initialization (which includes creating or loading objects that are used by the servlet in the handling of its requests, ability to log events, use its ServletContext refrence etc) is done in the Servlet's init method.
So if super.init() is not called the the class will not get its servletness.

b. If it is mandatory then why my sample servlet ran fine (without giving any error) ?

Your code ran fine because you just flushed some html code to the Response' PrintWriter.
Say for eg if you tried making use of the servlet parameters using Servlet Config object then the code would have thrown a exception.
Say in the doPost method you want to use the servlet paarmeter "NAME"


web.xml

This would have resulted in a exception as config object wasn't initialized since super.init() was not called.So getServletConfig() returned null and calling config.getAttribute("NAME") will result in NullPointerException.

c. What are the implications of
i. calling super.init(config) from within init(ServletConfig config) method in our servlet
ii. not calling super.init(config) from within init(ServletConfig config) method in our servlet


To make use use of the actual servletness of a servlet, it is required to call the super.init() in the overridden method.


 
Abhay Agarwal
Ranch Hand
Posts: 1376
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the reply
Understood
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic