Scala cookie-free session

I use the Scalatra environment to build a web application. The application relies on sessions, but I cannot use session cookies (because technically there is only one user who performs multiple sessions at the same time).

Each session has a unique session key that 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.

Now my question is: how can I store session information (i.e. state) in the Scalatra servlet without cookies, but simply as an identifier?

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

(Security is not a problem)

+5
source share
2 answers

I figured out how I can do this.

In every Scalatra servlet, I have access to a global servletContextone that implements the interface javax.servlet.ServletContext. Can I use two methods setAttribute(x: String, y: Any)and getAttribute(x : String)to store information about my sessions, where x - my unique ID and y - session information encoded as a case class Session.

In fact, 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
    }
}

Thus, I can save the state on the server without using cookies, only one unique identifier, which the client must provide as a GET value.

I assume this method can be applied to any servlet in Java and Scala that provides an instance servletContext, not just Scalatra.

+5
source

Good question.

, , a la Redis?

Scala debasishg, Scala, .

, , , ; cookie HttpSession

+1

All Articles