I would like to expire all my sessions in Tomcat. We test our product under Fitnesse and some sessions remain and the end of the session causes dependency between the tests. I do it by hand with the following code, but some sessions remain (I can check it with the http://localhost:8080/manager/html/list url)
public static void expireAllSessions() {
String[] applications = { "a", "b", "c", "d", "e" };
for (String application : applications) {
try {
expireAllSessions(application);
} catch (Exception e) {
logger.error(e);
}
}
}
private static void expireAllSessions(final String application) throws Exception {
// cf doc http://hc.apache.org/httpclient-3.x/authentication.html
HttpClient client = new HttpClient();
client.getParams().setAuthenticationPreemptive(true);
Credentials userPassword = new UsernamePasswordCredentials("tomcat", "tomcat");
client.getState().setCredentials(AuthScope.ANY, userPassword);
String url = "http://localhost:8080/manager/html/expire";
NameValuePair[] parametres = new NameValuePair[] {
new NameValuePair("path", "/" + application),
new NameValuePair("idle", "0")
};
HttpMethod method = new GetMethod(url);
method.setQueryString(parametres);
client.executeMethod(method);
}
Is there a way to do it more efficiently and immediate with no remaining session ?
Have you looked at Lamda Probe? For each of your web applications, you can view the contents of the session and expire them (all).
If you are keen on writing your own app to do this instead; Lamda Probe is open source, so you could take code from them to help accomplish your goal.
I'm assuming your applications are really independent contexts. I have done something similar to what you are asking using an
HttpSessionListener
for every context. The tricky part here is that you need to have a Session Collection that is loaded by the root class loader as opposed to the context class loader. This is how I remember it:Create a class which holds the active sessions for each context. This class must reside in the tomcat /lib directory so that it becomes accessible by every context. It can't be part of any of the contexts.
Create a listener for every context.
Registered each listener in the corresponding context's
web.xml
.You can then call the following line to invalidate everything from any context.
I'm synchronizing on the map just to be on the safe side.
You could use HttpSessionListener to save the references to sessions in a data structure and then use it at your leisure