Can we define constructor in Servlet class ?

Answer : Yes, we can define constructor in Servlet class…

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

[pastacode lang=”javascript” manual=”import%20javax.servlet.http.*%3B%0Aimport%20java.io.*%3B%0A%0Apublic%20class%20ConstructorServlet%20extends%20HttpServlet%0A%7B%0A%20%20String%20str1%2C%20str2%2C%20str3%3B%0A%20%20public%20ConstructorServlet()%0A%20%20%7B%0A%20%20%20%20str1%20%3D%20%22Constructor%22%3B%0A%20%20%7D%0A%20%20public%20void%20init()%0A%20%20%7B%0A%20%20%20%20str2%20%3D%20%22init()%20method%22%3B%0A%20%20%7D%0A%20%20public%20void%20service(HttpServletRequest%20request%2C%20HttpServletResponse%20response)%20throws%20ServletException%2C%20IOException%0A%20%20%7B%0A%20%20%20%20response.setContentType(%22text%2Fhtml%22)%3B%0A%20%20%20%20PrintWriter%20out%20%3D%20response.getWriter()%3B%0A%0A%20%20%20%20str3%20%3D%20%22%20service()%20method%22%3B%0A%0A%20%20%20%20out.println(%22%3Ch3%3E%22%2B%20str1%20%2B%20%22%3Cbr%3E%22%20%2B%20str2%20%2B%20%22%3Cbr%3E%22%20%2B%20str3%20%2B%20%22%3C%2Fh3%3E%22)%3B%20%0A%20%20%20%20out.close()%3B%0A%20%20%7D%0A%7D%20″ message=”” highlight=”” provider=”manual”/]

Output

[pastacode lang=”javascript” manual=”%20Constructor%0A%20%20%20%20init()%20method%0A%20%20%20%20service()%20method” message=”” highlight=”” provider=”manual”/]
Leave a Reply

Your email address will not be published. Required fields are marked *