正在将requestDestroyed
方法编写为servlet本身的一部分,就像下面在功能上等同于将requestDestroyed
重写为ServletRequestListener
的一部分一样吗?
public class MyServlet implements HttpServlet{
public void init(ServletConfig config) throws ServletException {
//init stuff
}
public void service(ServletRequest req,ServletResponse res)
throws ServletException {
try {
//do some stuff
} finally {
requestDestroyed(request);
}
}
private void requestDestroyed(HttpServletRequest request) {
//some clean up stuff only for this particular servlet
}
}
答案:不,这不是等效的。
有两个选项:
第一个选项:
要覆盖requestDestroyed
方法,您需要在自定义侦听器类中实现ServletRequestListener
。
例如:
我创建了一个RListener
类作为自定义侦听器:
public class RListener implements ServletRequestListener {
@Override
public void requestDestroyed(ServletRequestEvent servletRequestEvent) {
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequestEvent.getServletRequest();
System.out.println("All resources has been destroyed.")
//some clean up stuff only for this particular servlet
}
@Override
public void requestInitialized(ServletRequestEvent servletRequestEvent) {
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequestEvent.getServletRequest();
System.out.println("All resources has been initalized.")
//some initialization up stuff only for this particular servlet
}
}
在web.xml中添加<listener>
:
<listener>
<listener-class>com.example.RListener</listener-class>
</listener>
第二个选项:
您可以覆盖销毁方法,它是Servlet的生命周期方法:
示例:
public class MyServlet implements HttpServlet{
@Override
public void init(ServletConfig config) throws ServletException {
//init stuff
}
@Override
public void service(ServletRequest request, ServletResponse response)
throws ServletException {
try{
//do some stuff
}finally{
destroy();
}
}
@Override
public void destroy() {
//some clean up stuff only for this particular servlet
}
}