目次

Version 3, last updated by Debilski at Nov 27 20:17 UTC

Session State

Most web frameworks provide a session mechanism such that repeated requests from the same browser will be associated with the same data. This allows the primary key to the User object to be associated with user’s perception of a session so that once the user has logged in, they do not need to re-authenticate for each HTTP request.

Sessions are typically bound between the browser and the server via a cookie which contains a session identifier… a random number.

Web frameworks allow for associating keys with session values… for example setting “user_id” with “1”.

Type Safety

Scala and Lift strive to be type safe and to provide developers ways of writing correct code. Lift’s mechanism for associating data with sessions is type-safe and provide for globally a globally unique way to associate data with a session: SessionVar.

Defining Session Variables, SessionVar

To define a SessionVar, create a singleton that subclasses SessionVar:

object myData extends SessionVar[String]("Default")

myData is strongly typed as a String. Only a String may be put in or taken out. The expression "Default" is the default value for the given SessionVar. The expression is a passed “By Name” and is re-evaluated each time the SessionVar is read before it is written.

Nuts & Bolts

To set a value in a SessionVar: myData.set("foo") To access the data in the SessionVar: myData.is

A common pattern is to put a model object into a SessionVar. This takes the form:

object myModel extends SessionVar[Box[Model]](Empty)

This pattern allows you to avoid null testing, but instead use for comprehensions to traverse Box and Option constructs. See DPP’s Blog on the subject.