Table of contents
VoK Utilities
This page documents additional VoK utilities available to all VoK projects.
Support for Session
Provides a Session
object which gives handy access to the VaadinSession
:
Session.current
returns the currentVaadinSession
.Session["key"] = value
allows you to retrieve and/or store values into the sessionSession[MySessionScopedService::class] = MySessionScopedService()
allows you to store session-scoped services into the session. However, read below on how to do this properly.
Another important role of the Session
object is that it provides a default point to which you can attach your session-scoped services. For example, the user login module of your app can attach the LoggedInUser
service which contains both the currently logged-in user, and the means to log in and log out:
class LoggedInUser : Serializable {
val user: User? = null
private set
val isLoggedIn: Boolean
get() = user != null
fun login(username: String, password: String) {
val user = User.findByUsername(username) ?: throw LoginException("No such user $username")
if (!user.validatePassword(password)) throw LoginException("$username: invalid password")
this.user = user
}
fun logout() {
user = null
// http://stackoverflow.com/questions/26404821/how-to-restart-vaadin-session
Page.getCurrent().setLocation(VaadinServlet.getCurrent().servletConfig.servletContext.contextPath)
Session.current.close()
}
}
val Session.loggedInUser: LoggedInUser get() = getOrPut { LoggedInUser() }
By using the above code, you will now be able to access the LoggedInUser
from anywhere, simply by calling Session.loggedInUser.login()
. No DI necessary!
Note: the session is accessible only from the code being run by Vaadin, with Vaadin UI lock properly held. It will not be accessible for example from background threads - you will need to store the UI reference and call
ui.access()
from your background thread.
Cookies
There is a Cookies
singleton which provides access to cookies attached to the current request:
- Use
Cookies += Cookie("autologin", "secret")
to add a cookie; - Use
Cookies.delete("autologin")
to remove a cookie. - Use
Cookies["autologin"]
to access a cookie for the current request.