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

Why Servlet init(), not construtor

 
Pawanpreet Singh
Ranch Hand
Posts: 264
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Everyone, I have one query. As we know init() is the first method to call for initialization,
Can't i initialize a code by have a no args Servlet Constructor and write code there. I have checked and it works find.

Do we need to use a Constructor of a Servlet instead of init()...


package com;

import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;

public class Serve extends HttpServlet{

public Serve(){
String str = new String();
System.out.println("Serve() cons...");
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
response.setContentType("text/html");

PrintWriter pr = response.getWriter();
pr.println("serve the client");
}
}


-Pawan-
 
srinivas.b
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi pawan,

Good question.... see for a servlet the entire servletness comes when the container creates ServletConfig and ServletContext objects..
But unfortunately they are created after constructor call and before calling init() method.Before that servlet is like normal object.
so using constructor for initilization purpose means .. too early.

Hope you understand my point.
 
Pawanpreet Singh
Ranch Hand
Posts: 264
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic