Here is the code I use, instead of a filter, I use a listener so I don't
have to worry about setting urls.
This part is in web.xml
<listener>
<listener-class>yourpackage.SessionListener</listener-class>
</listener>
The majority of this code was found online (and I think came from
coreservlets.com)
package yourpackage;
import java.util.Date;
import java.util.Enumeration;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class SessionListener implements ServletContextListener,
HttpSessionListener{
private static int sessionCount=0;
protected transient final Log logger =
LogFactory.getLog(this.getClass());
public void contextInitialized(ServletContextEvent sce)
{
sce.getServletContext().setAttribute("sessionListener",this);
}
public void contextDestroyed(ServletContextEvent sce)
{
}
public synchronized void sessionCreated(HttpSessionEvent event){
HttpSession session = event.getSession();
// session.setMaxInactiveInterval(60);
synchronized (this) {
sessionCount++;
}
String id = session.getId();
Date now = new Date();
String message = new StringBuffer("New Session created on
").append(
now.toString()).append("\nID:
").append(id).append("\n")
.append("There are now ").append("" +
sessionCount).append(
" live sessions in the
application.").toString();
this.logger.debug("Created:" + message);
session.setAttribute("sessionstarted",new Date());
}
public void sessionDestroyed(HttpSessionEvent event) {
HttpSession session = event.getSession();
String id = session.getId();
synchronized (this) {
sessionCount--;
}
String message = new StringBuffer("Session destroyed"
+ "\nValue of destroyed session ID is
").append("" + id)
.append("\n").append("There are now ")
.append("" + sessionCount).append(
" live sessions in the
application.").toString();
this.logger.debug("Destroyed: " + message);
Date d = (Date)session.getAttribute("sessionstarted");
this.logger.debug("Session Length:
"+millisecondsToString(System.currentTimeMillis() - d.getTime()));
Enumeration stuff = session.getAttributeNames();
while (stuff.hasMoreElements()) {
String name = (String) stuff.nextElement();
// Object value = session.getAttribute(name);
this.logger.debug("Attribute Name:"+name);
}
}
public int getSessionCount() { return sessionCount; }
/**
* Converts time in milliseconds to a <code>String</code> in the
format Days HH:mm:ss.SSS.
* @param time the time in milliseconds.
* @return a <code>String</code> representing the time in the format
Days HH:mm:ss.SSS.
*/
public static String millisecondsToString(long time)
{
int milliseconds = (int)(time % 1000);
int seconds = (int)((time/1000) % 60);
int minutes = (int)((time/60000) % 60);
int hours = (int)((time/3600000) % 24);
int days = (int)((time/3600000)/24);
// hours += days*24;
String millisecondsStr = (milliseconds<10 ? "00" :
(milliseconds<100 ? "0" : ""))+milliseconds;
String secondsStr = (seconds<10 ? "0" : "")+seconds;
String minutesStr = (minutes<10 ? "0" : "")+minutes;
String hoursStr = (hours<10 ? "0" : "")+hours;
return new String(days+" Days
"+hoursStr+":"+minutesStr+":"+secondsStr+"."+millisecondsStr);
}
}
-----Original Message-----
From: David Kerber [mailto:[EMAIL PROTECTED]
Sent: Thursday, February 09, 2006 9:56 AM
To: Tomcat Users List
Subject: Re: Logging session timeouts
I got your code in, and it compiles, but I don't understand how I
configure the url-mapping you refer to. Could you point me to some docs
for that? I looked through the web.xml files (both the server one, and
the one for the app), but couldn't find anything about url-mapping or
filters that seemed to apply to this. It may be there, but I don't know
enough about it to recognize it.
Thanks!
Dave
Tim Lucia wrote:
Below is a filter which keeps track of how many sessions are attached to a
web app. The key part is the HttpSessionBindingListener interface.
Tim
/**
* J2EE "Filter" to count page hits. What it counts depends on the
url-mapping
* in web.xml.
*
* @author tim.lucia
*/
public class SessionCountFilter
implements Filter, HttpSessionBindingListener, Serializable
{
private final static Log logger =
LogFactory.getLog(SessionCountFilter.class);
public static final Hashtable sessions = new Hashtable();
public static int sessionCountHighWater = 0;
/**
* Container startup notification
*/
public void init(FilterConfig arg0) throws ServletException
{
logger.debug("init(): " + arg0);
}
/**
* Container shutdown notification
*/
public void destroy()
{
logger.debug("destroy()");
}
/**
* Process the container's filter request.
* @param request - Request object
* @param response - response object
* @param chain - next filter in the chain.
*/
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException
{
chain.doFilter(request, response);
HttpServletRequest httpRequest = (HttpServletRequest)request;
HttpSession session = httpRequest.getSession(false);
if (logger.isDebugEnabled()) {
logger.debug("Request " + httpRequest.getRequestURI() +
(session == null ? " returned no session" :
" belongs to session ID " + session.getId()));
}
// Bind to the session, if there is one, and it is new:
if (null != session && session.isNew()) {
session.setAttribute(toString(), this);
}
}
/**
* Implement HttpSessionBindingListener#valueBound
*/
public void valueBound(HttpSessionBindingEvent bindEvent)
{
HttpSession session = bindEvent.getSession();
final String sessionID = session.getId();
sessions.put(session, sessionID);
if (logger.isDebugEnabled()) {
logger.debug("[" + sessions.size() + "] CREATE: " +
sessionID);
}
sessionCountHighWater =
(sessionCountHighWater < sessions.size() ? sessions.size() :
sessionCountHighWater);
}
/**
* Implement HttpSessionBindingListener#valueUnbound
*/
public void valueUnbound(HttpSessionBindingEvent bindEvent)
{
HttpSession session = bindEvent.getSession();
final String sessionID = (String)sessions.get(session);
sessions.remove(session);
if (logger.isDebugEnabled()) {
logger.debug("[" + sessions.size() + "] DESTROY: " +
sessionID);
}
}
/**
* Return current count of sessions
* @return The number of sessions currently tracked
*/
public static int getSessionCount()
{
return sessions.size();
}
/**
* Return high water mark of number of sessions
* @return The high water mark of sessions tracked
*/
public static int getSessionCountHighWater()
{
return sessionCountHighWater;
}
/**
* Return string representation of this object
* @return a String representation of this object
*/
public String toString()
{
return getClass().getName() + "#" + hashCode();
}
}
-----Original Message-----
From: David Kerber [mailto:[EMAIL PROTECTED]
Sent: Thursday, February 09, 2006 9:38 AM
To: Tomcat Users List
Subject: Logging session timeouts
Is there any way of trapping session timeouts, so I can log them? I am
logging when a user logs in and when they explicitly log out, but would
like
to log when their session times out, if that is possible.
TIA!
Dave
---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]