Hvis man vil kan man godt lave noget.
Man kan bruge en SessionAttributeListener.
Jeg lavede et lille eksempel til at demo'e hvordan man kan gribe det an.
TimeoutEnforcer.java
--------------------
package test;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class TimeoutEnforcer implements HttpSessionAttributeListener {
private final static int CHECK_MS = 1000;
private LinkedList itms;
private Timer t;
public TimeoutEnforcer() {
itms = new LinkedList();
t = new Timer(true);
t.scheduleAtFixedRate(new Checker(itms), CHECK_MS, CHECK_MS);
}
public void attributeAdded(HttpSessionBindingEvent sbe) {
synchronized(itms) {
itms.add(new Item(sbe.getSession(), sbe.getName(), System.currentTimeMillis()));
}
}
public void attributeRemoved(HttpSessionBindingEvent sbe) {
synchronized(itms) {
itms.remove(new Item(sbe.getSession(), sbe.getName(), 0));
}
}
public void attributeReplaced(HttpSessionBindingEvent sbe) {
// do nothing
}
}
class Checker extends TimerTask {
private final static int TIMEOUT_MS = 10000;
private LinkedList ll;
public Checker(LinkedList ll) {
this.ll =ll;
}
public void run() {
long cut = System.currentTimeMillis() - TIMEOUT_MS;
synchronized(ll) {
Item o;
while((o = (Item)ll.peek()) != null && (o.getTime() < cut)) {
o.getSession().removeAttribute(o.getAttribute());
}
}
}
}
class Item {
private HttpSession session;
private String attribute;
private long time;
public Item(HttpSession session, String attribute, long time) {
this.session = session;
this.attribute = attribute;
this.time = time;
}
public HttpSession getSession() {
return session;
}
public String getAttribute() {
return attribute;
}
public long getTime() {
return time;
}
public boolean equals(Object o) {
if(o instanceof Item) {
Item oitem = (Item)o;
if(session.equals(oitem.session) && attribute.equals(oitem.attribute)) {
return true;
} else {
return false;
}
} else {
return false;
}
}
public int hashCode() {
return (session.hashCode() + attribute.hashCode());
}
}
web.xml
-------
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="
http://java.sun.com/xml/ns/j2ee" xmlns:xsi="
http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="
http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
<listener>
<listener-class>test.TimeoutEnforcer</listener-class>
</listener>
</web-app>
test.jsp
--------
<meta http-equiv="refresh" content="1">
<%
Object o = session.getAttribute("test");
if(o == null) {
out.println("Missing");
session.setAttribute("test", "something");
} else {
out.println("Present");
}
%>