This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
is it possible to make multiple initializations of a servlet depending on the request... Or servlet will be call init() once and i have to put other code in service() to handle the request. Please clarify.
Could you please make your question a little more clear? Is it that you have a servlet, and upon every request, you wish to have mulitple instances of the same servlet? Is that what you are tyring to do?
Vijayendra <br /> <br />"The harder you train in peace, the lesser you bleed in war"
Joined: Jul 21, 2004
I mean to say, if there are multiple requests coming to a servlet and depending on the kind of request, i have to initialize few parameters(like making connection to database depending on request)...(I know that init() is called only once when the first time request comes to server) So in that case, how can I intialize those parameter?? Do i need to write the code in service() for that.. Or i can use init() for that,if so, please clarify... Don't mind if my conception is a bit wrong,correct it.
If you want to handle different kinds of requests then u have to write the code on specific condition.... as the init() method is used only for creating the resources which are expensive like the database connections and other types becoz these are expensive if we want to create for each request ...
so, these kind of things will be done in init() and other processing logic is done using service()....
I think Julian's reply should have answered your question.
You have to keep in mind that the code that you include inside the init( ) method will be called only once per servlet instantiation, by the servlet container, when it instantiates a servlet. Only after the servlet has been instantiated, the service( ) methods starts getting called for every new HTTP request arriving. So since you are saying that you wish to have different type of initializations for different types of requests, its better if this logic goes inside the service( ) method.
You could try having 2 servlet definitions/mappings in your web.xml file for your serlvet which have different initialization parameters. Based on the initialization prameters, required code in the init method could be called accordingly. I haven't tried this so can't guarantee it will work, just an idea.