Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scalatra Session without cookies

I'm using the Scalatra framework to build a web application. The application relies on sessions, but I can't use session cookies (because technically there is only one user, which runs multiple sessions simultaneously).

Each session has a unique session key which I want to use as an identifier. I want this key to be sent as a GET or POST parameter instead of a cookie header.

My question now is: How can I store session information (i.e. a state) in a Scalatra servlet without cookies but just a parameter as identifier?

So far I tried to use the file system to store all session information, but this is too slow and unnecessary because the sessions only last a few seconds.

(Security is not an issue)

like image 479
Waboodoo Avatar asked Apr 19 '12 08:04

Waboodoo


1 Answers

I figured out how I can do it.

In every Scalatra servlet, I have access to the global servletContext which implements the javax.servlet.ServletContext interface. I can use its two methods setAttribute(x: String, y: Any) and getAttribute(x : String) to store information about my sessions, where x is my unique identifier and y is the session information encoded as a case class Session.

Effectively I have the following:

def storeSession(key : String, session : Session) {
    servletContext.setAttribute(attributePrefix + key, session)
}

def loadSession(key : String) : Session = {
    val session = servletContext.getAttribute(attributePrefix + key)
    if (session != null) {
        session match {
            case s : Session => s
            case _ => null
        }
    } else {
        null
    }
}

This way I can keep a state on the server, without using cookies, only a single unique identifier that the client has to provide as a GET value.

I guess this technique can be applied to any servlet in Java and Scala which provides an instance of ServletContext, not just Scalatra.

like image 63
Waboodoo Avatar answered Oct 17 '22 09:10

Waboodoo