Gaurav Daga
Gaurav Daga

Reputation: 343

Constructor for JSP ( Query out of curiosity)

I am wondering if there is any way you can write a constructor for a JSP. As technically JSP is just another Java Class, container will be generating a constructor for it during translation.

I am wondering if there is a way you can provide constructor to container for initializing the given JSP.

Upvotes: 1

Views: 557

Answers (1)

Cesar Loachamin
Cesar Loachamin

Reputation: 2738

Technically no you can't as you mention the container generate a Servlet class for each JSP and it creates a no-args constructor that will be called by the container, you can create another constructor but this wont't be used by the container to create the class.

As a Jsp is translated to a servlet class you can override the init() and destroy() methods as a normal servlet class, you also have to take in mind the servlet lifecycle the container creates only one instance of the servlet class and call only once the init method after the object is constructed and the destroy method when the object will be destroyed as the container is shutdown.

As we are using a Jsp page I suggest you to use the methods defined for the JspPage interface it defines also two convenient methods that you can override in your page, jspInit and jspDestroy.

<%! public void jspInit() {   
    //init code 
 }  
%> 
<%! public void jspDestroy() {   
    //destroy code 
 }  
%> 

Upvotes: 2

Related Questions