Can we define constructor in Servlet class ?

  • Yes, we can define constructor in Servlet class.
  • Constructor may be a Default Constructor or Parameterised Constructor. If we didn’t write any constructor then the default constructor will be executed. Because, to read init parameters of a servlet we need servlet config object in the life cycle of the servlet.
  • Servlet config object is created after the execution of the constructor.

Servlet Constructor

Sample Code

import javax.servlet.http.*;
import java.io.*;

public class ConstructorServlet extends HttpServlet
{
  String str1, str2, str3;
  public ConstructorServlet()
  {
    str1 = "Constructor";
  }
  public void init()
  {
    str2 = "init() method";
  }
  public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    str3 = " service() method";

    out.println("<h3>"+ str1 + "<br>" + str2 + "<br>" + str3 + "</h3>"); 
    out.close();
  }
} 
JavaScript

Output

 Constructor
    init() method
    service() method
JavaScript

Categorized in:

Tagged in:

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,