jspInit函数与jspDestroy函数(转)

来源:互联网 发布:安卓网游源码 编辑:程序博客网 时间:2024/06/05 22:53

若要在jsp页面开始执行时进行某些数据的初始化,可以利用jspInit函数完成。此函数将在jsp页面被执行时调用,且当jsp页面重新整理时,并不会被再度执行。当关闭服务器时,jspDestroy函数将被执行,可以利用该函数进行数据的善后处理工作。下面举个简单的例子说明,文件InitDes.jsp代码如下:

<%@ page contentType="text/html; charset=GB2312"%> 
<%! 
public void jspInit() 

    System.out.println("jspInit is called!"); 
}

public void jspDestroy() 

    System.out.println("jspDestroy is called!"); 

%> 
<HTML> 
<HEAD><TITLE>jspInit函数与jspDestroy函数的使用</TITLE></HEAD> 
<BODY> 
<CENTER> 
<FONT SIZE = 5 COLOR = blue>jspInit函数与jspDestroy函数的使用</FONT> 
</CENTER> 
<HR><BR> 
</BODY> 
</HTML>

首次执行此页面时,Resin服务器输出如下:
Resin 1.2.2 -- Tue Jan 16 09:53:18 PST 2001
http listening to *:8080
srun listening to 127.0.0.1:6802
jspInit is called!
刷新此页面数次后,Resin服务器输出仍然如上。
此时,如果关闭服务器,则输出如下:
Resin 1.2.2 -- Tue Jan 16 09:53:18 PST 2001
http listening to *:8080
srun listening to 127.0.0.1:6802
jspInit is called!
closing server
jspDestroy is called!
由此,我们得到启发,在数据库的开发过程中,可以利用jspInit函数来进行数据库的连接工作,用jspDestroy函数来进行数据库的关毕工作



Differences between jspInit(),_jspService, jspDestroy
2012-04-09 18:54

JSP contains three life cycle methods namely jspInit( ), _jspService() and jspDestroy(). In these, jspInit() and jspDestroy() can be overridden and we cannot override _jspService().

The contents what we write in the JSP will go into _jspService() because we are implicitly implementing it. If we again try to override it explicitly, JSP compliler will giver error as ‘the method is already implemented and cannot override’. But in the case of other two methods we are not implementing it in the JSP. Therefore the JSP compiler will allow to override jspInit() and jspDestroy().

To show this difference _jspService() method is prefixed with ‘_’ by the JSP container and the other two methods jspInit() and jspDestroy() has no special prefixes.

 

 

 注意:这里是jspInit和jspDestroy而不是_jspInit和_jspDestroy方法。JSP容器会在调用_jspInit和_jspDestroy方法后调用自定义的jspInit和jspDestroy方法。
  个人认为,这里的使用了模板方法模式,jspInit和jspDestroy为模板方法_jspInit和_jspDestroy方法的钩子方法。


原创粉丝点击