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.
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 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() {
        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="" xmlns="" xsi:schemaLocation="" id="WebApp_ID" version="3.0">
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.

No comments :

Post a Comment