Can I instantiate an object in the init method of a JSP and use the same object within the service method during request processing?

Simon Brown

If you have an instance (or page level) variable defined, then the answer is yes ... you can instantiate it and use it elsewhere in your JSP.

The jspInit() method will only get called when the JSP is initialised so the object will be available for the lifetime of the page. I'm not saying that you should directly open or hold on to database connections from JSP pages, but here's an example that will help explain what happens.

Imagine that you have declared a page level variable using the <%! ... %> tags. This variable could be a JDBC Connection.

In your jspInit() method, you could perform the connection to the database and set your connection variable. As the jspInit() method only gets called once, the connection is only opened once.

You can then use your connection variable within your JSP page as and when necessary, remembering to close it in the jspDestroy() method.