[an error occurred while processing this directive]

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.


add the following action snippet to the following struts.xml file. 


<action name="GetSession" class="net.roseindia.GetSession">

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.


package net.roseindia;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;
import java.util.*;

public class GetSession extends ActionSupport implements SessionAware{

  private Map session;
  public String execute() throws Exception{
    return SUCCESS;

  public void setSession(Map session){
    session = this.getSession();

  public Map getSession(){
    return session;


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.   


<%taglib prefix="s" uri="/struts-tags" %>
<%@page language="java" import="java.util.*" %>
    <title>Get Session Example!</title>
    <h1><span style="background-color: #FFFFcc"> Session Example! </span></h1>
    <b>Session Context: </b><%=session.getSessionContext() %><br>
    <b>Session Time: </b><%=new Date(session.getLastAccessedTime())%>

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:


[an error occurred while processing this directive]