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 ActionSupport
class
.
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.
Description:
add the following action snippet to the following struts.xml file.
struts.xml
<action name="GetSession" class="net.roseindia.GetSession"> <result>/pages/staticparameter/GetSession.jsp</result> </action> |
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.
GetSession.java
package net.roseindia;
|
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.
GetSession.jsp
<%@ taglib prefix="s" uri="/struts-tags" %> <%@page language="java" import="java.util.*" %> <html> <head> <title>Get Session Example!</title> </head> <body> <h1><span style="background-color: #FFFFcc"> Session Example! </span></h1> <b>Session:</b><%=session%><br> <b>Session Context: </b><%=session.getSessionContext() %><br> <b>Session Time: </b><%=new Date(session.getLastAccessedTime())%> </body> </html>
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: