Skip to main content

Can a Servlet have a Constructor

Points To Remember
  • Servlet is a java class that implements javax.servlet.Servlet interface.
  • Servlets are initialized by the servlet containers using init() method.
  • Servlets like any other java class can have constructors.
  • Servlet must have a no argument constructor in case it have a non zero arguments constructor.
  • Servlet needs an object of ServletConfig for initialization.
  • Interfaces cannot have constructors.
Can we have Constructors in a Servlet ?
Yes we can, please read How a servlet is initialized by the servlet container. So this article will make clear, why we cannot use a constructor for initializing a servlet.

However there is no problem in having a constructor in a servlet. We can have both argumented and no arguments constructor in a servlet.
Example
What we are trying to do is to create a simple servlet with a constructor and assign a value to a String variable named as "msg".

Servlet : ServletConstructor

package com.ekiras.demo;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletConstructor extends HttpServlet {
private static final long serialVersionUID = 1L;

private String msg;

public ServletConstructor() {
super();
System.out.println("HI i am getting initialized");
this.msg = "Servlet Constructor Demo";
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Get method --> msg = " + msg);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}

}

Deployment Descriptor : web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Test</display-name>
<welcome-file-list>
<welcome-file>ServletConstructor</welcome-file>
</welcome-file-list>

<servlet>
<servlet-name>ServletConstructor</servlet-name>
<servlet-class>com.ekiras.demo.ServletConstructor</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletConstructor</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
When we run the above application in the web server like tomcat we will get the following output.
HI i am getting initialized
Get method --> msg = Servlet Constructor Demo
So this makes it clear that there is no problem in having a constructors in a servlet.

Comments