"Garcia Buendia, Carlos" wrote:
>
> I'm opening a database connection using JDBC 2.1.
> I associate this connection to a HttpSession.
>
> I'd like to know some way to control the instant when the
> HttpSession close. That way I can make a rollback and close
> the database connection properly.
>
You can get notified of every significant event in the life
of a servlet. In this case, you're interested in the Session
Lifecycle. You should check out:
java.servlet.http.HttpSessionBindingListener
If you add an object that implements this interface into
the session, then when the object is removed from the
session you get a callback. Sort of like this:
---------8<----------8<-----------------------------------
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SessServlet extends HttpServlet {
static class SessObj implements HttpSessionBindingListener {
public int cnt = 0;
public void valueBound(HttpSessionBindingEvent event) {
System.out.println("SessServlet.SessObj.valueBound()");
}
public void valueUnbound(HttpSessionBindingEvent event) {
// >>> rollback here <<<
System.out.println("SessServlet.SessObj.valueUnbound()");
}
}
public void doGet(HttpServletRequest req, HttpServletResponse rsp)
throws ServletException, IOException
{
PrintWriter out = rsp.getWriter();
rsp.setContentType("text/plain");
HttpSession s = req.getSession(true);
SessObj sobj = (SessObj)s.getAttribute("SessObj");
if (sobj==null) {
sobj = new SessObj();
s.setAttribute("SessObj", sobj);
out.println("Sess Servlet:new session");
} else {
String query = req.getQueryString();
if ("logout".equals(query)) {
s.invalidate();
out.println("Sess Servlet:logging out of session");
} else {
sobj.cnt++;
out.println("Sess Servlet:in session:cnt="+sobj.cnt);
}
}
}
}
---------8<----------8<-----------------------------------
Depending on where your stdout goes, you'll see a bind
message when you start a new session, and an unbind
message when the session ends. You can force the session
to end by calling the servlet with a query string of
"logout".
--
Christopher St. John [EMAIL PROTECTED]
DistribuTopia http://www.distributopia.com
___________________________________________________________________________
To unsubscribe, send email to [EMAIL PROTECTED] and include in the body
of the message "signoff SERVLET-INTEREST".
Archives: http://archives.java.sun.com/archives/servlet-interest.html
Resources: http://java.sun.com/products/servlet/external-resources.html
LISTSERV Help: http://www.lsoft.com/manuals/user/user.html