Win a copy of The Business Blockchain this week in the Cloud forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What is the need of init method

 
Abhishek KumarSoni
Ranch Hand
Posts: 61
Chrome Firefox Browser
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello friends
Could someone please explain me what is the need of init method in a servlet life cycle .We use constructor to load the class and init() function to initialize it(for task like DB connectivity).. why we need init a method separately for initializing a servlet.why constructor can not be used to initialize a servlet.
 
Paul Clapham
Sheriff
Posts: 21542
33
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's one of the questions in the Ranch's Servlets FAQ. Have a look, and check out some of the other FAQ entries which you might also have been tempted to ask.
 
Paul Anilprem
Enthuware Software Support
Ranch Hand
Posts: 3817
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Let's say you need DB url to connect to the db in your servlet at the time of initialization. How will you get the DB url in the constructor?
Of course, they could have forced servlets to have a constructor that takes ServletConfig as an argument but init provides a lot cleaner approach.
 
Slim Soltani Dridi
Greenhorn
Posts: 20
Java Spring Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want to have a connection to the Database. You can do that in the constructor and init method. But it's not that the most important.
To have a connection to the database, you have to provide either a URL/URI or a connection Path (DBURL).

You can implement that directly in the constructor, but if you want to change the DBURL / Path of Database, you have to change your code and recompile. It's not a good idea.

The good point is to set the DBURL in init parameter either in the servlet or in the context application.

In the servlet you have to create an init parameter like that :


In the application context :


It's easier and better to change the value in the Web.xml (even the designer can do that) to change directly the code itself.
And web.xml can be read only when the class become a true servlet (during the call of init method).

init method can have an access to ServletConfig to have either servlet init param or context application init param.

or
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic