An action Context behaves like a map, with some particularities.
The Application context:
The Application context is an application scope map that you can use to save any information across your whole application. It is a good place for a cache for example.
Context application = action.getApplication(); Collection<User> users = (Collection<User>) application.getAttribute("users"); // or set anything you want: application.setAttribute("myCache", theCache); // Note: that does not make sense and will throw an UnsupportedOperationException: application.reset();
The Session context:
The Session context can be used to save state across multiple web requests from the same client. Authentication is done that way so it allows a context reset when you want to say bye to the user.
Context session = action.getSession(); session.setAttribute("user", user); // reset the session session.reset();
The Cookies context:
Cookies are handled automatically by Mentawai and placed in the Cookies context. You can easily access all client's cookies, remove any cookie or add any cookie that will be sent back to the browser for some client-side state.
Context cookie = action.getCookies(); // read any cookie sent by the browser: String someCookieValue = (String) cookies.getAttribute("myCookie"); // add a cookie cookies.setAttribute("username", username); // it will be sent back by the browser and persisted there... // remove a cookie cookies.removeAttribute("username"); // it will also be removed from the client-side // when the response is sent back to the browser... cookies.reset(); // throws UnsupportedOperationException - does not make sense
More control for your cookies:
If you want to specify the cookie attributes, such as max age, domain, etc. all you have to do is set a whole Cookie object in the context, instead of just a String.
Cookie cookie = new Cookie("myCookie", "hello cookies!"); cookie.setMaxAge(60 * 60 * 24); // one day... cookie.setPath("/"); Context cookies = action.getCookies(); cookies.setAttribute("myCookie", cookie);