Question

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)

Was it helpful?

Solution

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.

OTHER TIPS

Nice question.

Rather than storing state to disk and the performance hit that that entails, how about storing in-memory a la Redis?

There's a Scala implementation by debasishg, a heavy in the Scala community, which may fit the bill.

On the stateless side of the fence, in Spray, for example, this was suggested to me as alternate means to maintaining state server-side; i.e. store client cookie identifier to in-memory cache vs. relying on HttpSession

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top