tags:

views:

62

answers:

1

I'm trying to figure out how to enforce a 5 minute per post/action rule.

I'm developing a web application with Wicket in Java and I've got a session class which I was planning on using to keep track of these timers on a per-user basis. I wasn't planning on storing the timestamp in a database.

I've got the method below in my session class, and now I'm trying to figure out how to go about storing and checking that there's a 5 minute difference between the last time the user posted and the current time.

If, lets say java.util.Date, would be suitable for this, how do I get the difference between two of these, in minutes.

public boolean isAllowedToPost() {  
    if(null OR has 5 minutes passed since last post) {  
        // set the new timestamp      
        return true;    
    }  
    else   
    {   
        return false;  
    }  
}
+2  A: 

The most robust way would be storing the timestamp in a database, since the client could simply logout/login or trash the session (delete cookie or restart webbrowser) to obtain a new session.

If you insist in storing it in session at any way, then one of the ways would be setting the timestamp during post() and use it as comparision material in isAllowedToPost(). You can obtain the current timestamp by System#currentTimeMillis(). No need for java.util.Date.

Kickoff example (assuming that this whole bean is session scoped):

private static final long MAX_WAIT_FOR_POST = 300000L; // ..ms = 5 minutes.
private long lastPost; // Defaults to 0 anyway.

public void post() {
    lastPost = System.currentTimeMillis();
    // ...
}

public boolean isAllowedToPost() {
    return (lastPost + MAX_WAIT_FOR_POST) < System.currentTimeMillis();
}
BalusC
Thanks BalusC. I appreciate the input on why I should store the timestamp in the database and not in the session. I haven't set up any database connectivity yet so that's why I want to store it in the session for the time being.Thanks again.
John
You're welcome.
BalusC