Sessions are created on demand via: req.ifSession() or req.session().
Sessions have a lot of uses cases but the most commons are: authentication, storing information about current user, etc.
A session attribute must be a String or a primitive. The session doesn't allow storing of
arbitrary objects. It's intended as a simple mechanism to store basic data.
{
get("/", req -> {
Session session = req.session();
// set attribute
session.set("foo", "bar");
// get attribute
return session.get("foo").value();
});
}The previous example will use an in-memory session. The next example uses a cookie:
{
cookieSession();
get("/", req -> {
Session session = req.session();
// set attribute
session.set("foo", "bar");
// get attribute
return session.get("foo").value();
});
}The cookie session store depends on the application.secret property. The cookie will be signed with the value of this property.
As an alternative to the memory or the cookie stores, you can choose any one of the high performance session stores provided by {{jooby}}. There are provided session stores for redis, memcached, mongodb, cassandra, couchbase, hazelcast and a lot more.
{
cookieSession();
get("/", req -> {
Session session = req.session();
// set attribute
session.set("foo", "bar");
// get attribute
return session.get("foo").value();
});
}There is no timeout for sessions from the perspective of the server. By default, a session will expire when
the user close the browser (a.k.a session cookie) or the cookie session has expired via the maxAge attribute.
Session store implementations might or might not implement a server timeout.
The session.cookie.maxAge sets the maximum age in seconds. A positive value
indicates that the cookie will expire after that many seconds have passed. Note that the value is
the maximum age when the cookie will expire, not the cookie's current age.
A negative value means that the cookie is not stored persistently and will be deleted when the browser exits.
Default maxAge is: -1.
If the application.secret property has been set, the session cookie will be
signed with it.
The session.cookie.name indicates the name of the cookie that hold the session ID, by
default: jooby.sid. The cookie's name can be explicitly set with
cookie.name("name") on Session.Definition#cookie().