Friday, February 10, 2017

Constructor vs Init method in Servlet - JEE Interview Question

Can we have a Constructor in Java Servlet? or Why do we need a constructor in Servlet if there is already an init() method for initializing Servlet, or what is the difference between init() method and constructor in Servlet are a couple of questions I have seen in various Java web developer interviews. All of these questions are related to the role of the constructor and init() method in the Servlet implementation class. Though I had shared few thoughts on this, when I wrote the top 10 Servlet questions for Java programmers,  I thought to cover it in more detail here.

In this article, I will try to answer each of these questions in detail. The key thing to remember is that Servlet is special in the sense that their life cycle is managed by web containers like Tomcat and Jetty. They are responsible for creating instances of Servlet and destroying them when they don't have enough resources or need to support so many instances of Servlets.

Let me first answer the question, Can we create a constructor in Servlets? and then I will answer why you should be using the init() method for Servlet initialization by describing the difference between constructor and init() method.

Btw, if you are new into Servlet and JSP then I also suggest you go through a comprehensive course to learn Servlet and JSP in depth. If you need a recommendations then I suggest you check out JSP, Servlet, and JDBC for Beginners: Build a Database App course on Udemy by Chad Darby. One of the hands-on course to learn Servlet and JSP.

Can we define Constructor in Servlet?

The short answer to this question, Yes, Servlet implementation classes can have constructor but they should be using init() method to initialize Servlet because of two reasons, first you cannot declare constructors on an interface in Java.

This means you cannot enforce this requirement to any class which implements the Servlet interface and second, Servlet requires ServletConfig object for initialization which is created by container as it also has a reference of ServletContext object, which is also created by the container.

Servlet is an interface defined in javax.servlet package and HttpServlet is a class and like any other class in Java they can have constructors, but you cannot declare constructor inside interface in Java. If you don't provide an explicit constructor than compiler will add a default no-argument constructor in any Servlet implementation class.

Another reason that you should not initialize Servlet using constructor because Servlets are not directly instantiated by Java code, instead containers create there instance and keep them in the pool.

Since containers from web servers like Tomcat and Jetty uses Java Reflection for creating an instance of Servlet, the presence of no-argument constructor is a must. So, by any chance, if you provide a parametric constructor and forget to write a no-argument constructor, web container will not be able to create an instance of your Servlet, since there is no default constructor.

Remember Java compiler doesn't add default no-argument constructor if there is a parametric constructor present in class. That's why it's not advised to provide a constructor in Servlet class. Now let's see some difference between Constructor and init method in Java Servlet

Difference between Constructor and init method in Servlet

In a real-world application, you better use init() method for initialization, because init() method receives a ServletConfig parameter, which may contain any initialization parameters for that Servlet from web.xml file. Since web.xml provides useful information to web container e.g. the name of Servlet to instantiate, ServletConfig instance is used to supply initialization parameter to Servlets.

You can configure your Servlet based upon settings provided in ServletConfig object e.g. you can also provide environment-specific settings e.g. the path of temp directory, database connection parameters (by the way for that you should better leverage JNDI connection pool) and any other configuration parameters.

You can simply deploy your web application with different settings in web.xml file on each environment. Remember, init() method is not chained like a constructor, where superclass constructor is called before subclass constructor executes, also known as constructor chaining.

Can Servlet define constructor in Java

That's all on this post about the difference between constructor and init method of Servlet. We have seen that the container uses web.xml to get Servlet's name for initialization and uses Java Reflection API, primarily class.newInstance() method to create an instance of Servlet, which means Servlet class must need a default no-argument constructor.

We have also seen that why Servlet cannot have user-defined constructor, mainly because Servlet as the interface cannot guarantee it and web container creates an instance of Servlet and has access to Context and Config object which is not accessible to the developer.

Always prefer to init() method for initializing Servlet than the constructor, because ServletConfig object is supplied to init() method with configuration parameters.

Further Learning
Java Web Fundamentals By Kevin Jones
Spring Framework 5: Beginner to Guru
JSP, Servlets and JDBC for Beginners: Build a Database App

If you like this Java Web developer Interview question and hungry for more don't forget to check the following questions as well :
  • What is the difference between Struts 1 and Struts 2 MVC framework? (answer)
  • What is the difference between forward() and sendredirect() method? (answer)
  • How to avoid double submission of form data in Servlet? (answer)
  • What is load-on-startup tag do in web.xml? (answer)
  • What is JSESSIONID in Java Web application? (answer)
  • How many bean scope is available in Spring framework? (answer)
  • Difference between Setter and Constructor injection in Spring? (answer)
  • What is difference between Web and Application Server? (answer)
  • Difference between GET and POST HTTP request? (answer)
  • What is difference between URL encoding and URL Rewriting? (answer)
  • Difference between include directive and include action in JSP? (answer)
  • How to define application wide error page in JSP? (answer)
  • What is difference between ServletConfig and ServletContext? (answer)
  • How to escape XML metacharacters in JSP? (answer)

No comments :

Post a Comment