aspose file tools
The moose likes Servlets and the fly likes init() vs. static {} Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Meteor in Action this week in the JavaScript forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "init() vs. static {}" Watch "init() vs. static {}" New topic
Author

init() vs. static {}

Herbert Wilson
Greenhorn

Joined: Nov 18, 2003
Posts: 3
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

Joined: Jan 10, 2002
Posts: 62464
    
  68

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


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Arun Giridhar
Ranch Hand

Joined: Mar 10, 2012
Posts: 163

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 {...}


if there is no tool make your own.
Devaka Cooray
ExamLab Creator
Sheriff

Joined: Jul 29, 2008
Posts: 3408
    
  64

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.


Author of ExamLab ExamLab - a free SCJP / OCPJP exam simulator
What would SCJP exam questions look like? -- Home -- Twitter -- How to Ask a Question
Paul Clapham
Sheriff

Joined: Oct 14, 2005
Posts: 19411
    
  10

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 agree. Here's the link: http://aspose.com/file-tools
 
subject: init() vs. static {}