permaculture playing cards*
The moose likes Servlets and the fly likes servlet init method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "servlet init method" Watch "servlet init method" New topic
Author

servlet init method

Jawahar Rajan
Ranch Hand

Joined: Feb 28, 2002
Posts: 38
I am trying out a simple servlet (just started learning Servlets and JSP's)
In the init method of my servlet I am trying to write out to the console (dos console).
I am not able to do so, but if I do this in the service method I am sucessful
see below:
import javax.servlet.*;
import java.util.Enumeration;
import java.io.IOException;
public class ConfigDemoServlet extends ReserveConfigServlet {
public void init(ServletConfig config) throws ServletException {
Enumeration parameters = servletConfig.getInitParameterNames();
while (parameters.hasMoreElements()) {
String parameter = (String) parameters.nextElement();
System.out.println("Parameter name : " + parameter);
System.out.println("Parameter value : " +
servletConfig.getInitParameter(parameter));
}
}
public void destroy() {
}
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
System.out.println("Works here");
}
public String getServletInfo() {
return null;
}
public ServletConfig getServletConfig() {
return null;
}
}
I am using Tomcat versio 4.12. I have understood that the servlet container call the init method when the servlet is first instantiated and passes it a ServletConfig object.
Any help is welcome
TIA
Jawahar
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12756
    
    5
I don't know for sure why you didn't see output from the init method, but I want to point out that if you use:

Your init method may have thrown an exception at the line.
Enumeration parameters = servletConfig.getInitParameterNames();
since servletConfig is undefined
Bill
Gaia Nathan
Ranch Hand

Joined: Aug 01, 2001
Posts: 62
Hi,
Like Jawahar, I'm also a newbie in this field; trying to learn as much as possible. I tried Jawahar's code, and like u said it did throw an exception at this line:

since ServletConfig is undefined. I modified the code and included the call to super.init(config);
but ended up with a null pointer exception saying:

Below is my sample program:

Why is this happening?
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12756
    
    5
What does the stack trace say about the origin of that exception?
Bill
 
wood burning stoves
 
subject: servlet init method
 
Similar Threads
Destroy Method in servlet constructor
servlet not running but examples does
How to access application level object outside from web container?
problem with servlet's init
environment variable referance in Web.xml