Every JSP web page is based on HttpJspBase Java class. HttpJspBase class has two important methods-
jspInit()
jspDestroy()
These two methods are called automatically during the lifecycle of a JSP web page i.e. from the time when it is initialization by the Server to the time when it is destroyed or unloaded by the Server.
jspInit()
JSP method jspInit() is automatically called by the Server when a JSP page is initialized or executed for the first time. This method has a public access-modifier and it doesn't accept nor returns any value.
In this method, we can add code some initialization code. For example, it could be initializing an object to a value or
we could initialize objects to values or we can open a database connection.
public void jspInit()
{
}
jspDestroy()
JSP method jspDestroy() is automatically called by the Server when a JSP page is destroyed or unloaded. Like jspInit() method, jspDestroy() method also has a public access-modifier and it doesn't accept nor returns any value.
We can add a clean-up code in jspDestroy() method. For example ,we can add code in jspDestroy() method to make sure it all the open database connections are closed or
can make unused objects point to null to save the memory.
public void jspDestroy()
{
}
Advertisement
Example of jspInit() and jspDestroy() method
We have created a JSP web page where we have initialized a String object to a value using jspInit() method.
Builtin.jsp
<html>
<head>
<title>JSP Built-in methods </title>
</head>
<body>
Explaining JSP builtin methods jspInit() and jspDestroy().
<%!
String str;
public void jspInit()
{
str = "Hello from the jspInit()";
}
public void jspDestroy()
{
str=null;
}
%>
<br/>
The value in String is - <%= str %>
</body>
</html>
executing this JSP page displays content of String object to the user and when the user closes this JSP page,
the String object is made to point to null so that it can be taken off the memory by Garbage Collector and thus saving memory.