• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

init() vs. static {}

 
Herbert Wilson
Greenhorn
Posts: 3
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the difference between using an init() method as opposed to a static block in a servlet? They both are called once when the servlet is loaded.
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65123
91
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Big difference.
The static block is executed when the class is loaded. The init method is called by the container once important structures like the servlet context and the servlet config have been created and are available for the init() method to peruse.
bear
 
Arun Giridhar
Ranch Hand
Posts: 181
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sorry to wake up old thread !

I too want to know this difference as per the design
>> one can choose a property file to store name/value pair and later at static block load (property file) resource and can configure resources . So what is the need of init(Servlet Config) when we can configure at static {...}
 
Devaka Cooray
ExamLab Creator
Marshal
Pie
Posts: 4595
302
Chrome Eclipse IDE Google App Engine IntelliJ IDE jQuery Postgres Database Tomcat Server
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Arun Giridhar wrote:So what is the need of init(Servlet Config) when we can configure at static {...}

As Bear said, that method is called when the servlet container has the ServletConfig object readily available for that servlet. See what you can do with ServletConfig and ServletContext.

I don't understand what it has to do with loading a .properties file though, but it must be noted that a servlet is not the right place to load/configure resources.
 
Paul Clapham
Sheriff
Posts: 21322
32
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The other difference is that the static block is only executed once, whereas the init() method is executed once for each instance of the servlet. Now, it's not very common to have more than one instance of a servlet but there are cases when it happens.
 
Arun Giridhar
Ranch Hand
Posts: 181
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Paul Clapham wrote:The other difference is that the static block is only executed once, whereas the init() method is executed once for each instance of the servlet. Now, it's not very common to have more than one instance of a servlet but there are cases when it happens.

I have come across this ^^
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic