Saturday, 23 April 2016

Can we get ServletConfig inside constructor of Servlet ?


It is not possible to get ServletConfig inside constructor of Servlet.

Scenario
Given a servlet
public class myServlet extends HttpServlet{
  int allowable_connections;

  public myServlet() {    // constructor
   allowable_connections = 
       getServletConfig().getInitParameter("allowable_connections");
  }

 public void service(HttpServletRequest req, 
               HttpServletResponse resp) throws Exception{
   PrintWriter out = request.getWriter();
   out.println("Allowable connections are:"+allowable_connections);
 }
}

Given allowable_connections init parameter's value is defined as 10 in the web.xml for the servlet, what will happen when a POST request is received for this servlet ?


Answer
The servlet will not be loaded.
Constructor is too early to call getServletConfig method.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.