Fork me on GitHub

Session holds information about a user session. It’s a wrapper around the standard Servlet HTTP Session abstraction.
You can retrieve the current session via Request.getSession(), Request.getSession(boolean create) or RouteContext.getSession().

See below a snipet code about how to work with session in Pippo:

// authentication filter
GET("/contact.*", routeContext -> {
	if (routeContext.getSession("username") == null) {
		routeContext.setSession("originalDestination", routeContext.getRequest().getContextUriWithQuery());	
		routeContext.redirect("/login");
	} else {
		routeContext.next();
	}
});

// process login submit
POST("/login", routeContext -> {
	String username = routeContext.getParameter("username").toString();
	String password = routeContext.getParameter("password").toString();
	if (authenticate(username, password)) {
		String originalDestination = routeContext.removeSession("originalDestination");
		routeContext.resetSession();

		routeContext.setSession("username", username);
		routeContext.redirect(originalDestination != null ? originalDestination : "/contacts");
	} else {
		routeContext.flashError("Authentication failed");
		routeContext.redirect("/login");
	}
});

Pippo allow you to customize Session via pippo-session module.

A session manager is composed of two parts:

  • SessionDataStorage that is a CRUD over StoreData
  • SessionStrategy that is responsible to fetch the session id from a HttpRequest (for example from a cookie or header).

The default session manager comes with a MemorySessionDataStorage that keeps the session data in a Map and a CookieSessionStrategy that saves/retrieves the session id to/from a cookie.
All the implementation is based on Response.finalizeResponse(). On this method I try to store/delete the session id and the session data. The main idea is that ALL the methods from Response that commit the response must call finalizeResponse().

See below a snipet code about how to work with cookie session in Pippo:

public class MyApplication extends Application {

    @Override
    protected void onInit() {
		// add routes here
    }

    @Override
    protected RequestResponseFactory createRequestResponseFactory() {
        SessionDataStorage sessionDataStorage = new CookieSessionDataStorage();
        SessionManager sessionManager = new SessionManager(sessionDataStorage);

        return new SessionRequestResponseFactory(this, sessionManager);
    }

}

Pippo also has the following SessionDataStorage modules:

A session is available automatically to templates for the rendering page process, which allows you to reference any session attribute in your template. Below is a simple example using freemarker as template engine:

<#if (session)??>
	<div>${session.id}</div>
    <div>${session.username}</div>
<#else>

For a fully functional demo related to custom session please see pippo-demo-session module.