Accessing Session Object
In this section, we will develop a simple application
to access the framework resources like the session object, session context and
the last accessed session time. To access the session, you need an action class
implementing the SessionAware interface and extending
org.apache.struts2.interceptor.SessionAware Interface: Actions that need access to the user's HTTP session should implement this interface. This interface is only relevant if the Action is used in a servlet environment. Note that using this interface makes the Action tied to a servlet environment, so it should be avoided if possible since things like unit testing will become more difficult.
add the following action snippet to the following struts.xml file.
Now, create a JavaBean (GetSesstion.java). This is a simple POJO (Plain Old Java Object). Here, we implement SessionAware interface.
The setSession() method sets the session in a Map object. It is called at the running time.
Now, we create a jsp page for viewing the session object, session context and session time. The session object provides information about the session, getSessionContext() method provides the information about the session context and getLastAccessedTime() provides date and time when the last session is accessed.
Finally, open the web-browser and type the http://localhost:8080/struts2tutorial/roseindia/GetSession.action in the address bar. It displays the information about framework session, session context and last accessed session time.
Output of this application: