File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

servlet init method

 
Jawahar Rajan
Ranch Hand
Posts: 38
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13045
6
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 62
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13045
6
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What does the stack trace say about the origin of that exception?
Bill
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic