How to use parameters, request and session objects present in ActionContext?

In Struts2, Session Map and Request Map are wrappers for the underlying HttpServletRequest and Session objects.

If you only need to access attributes, use the wrappers.

Use ActionContext to get them (both the wrappers and the underlying HTTP objects) only if you are inside an Interceptor or a POJO.

If you are inside an Action, the best practice is to implement an Interface that will automatically populate your Action’s object:


To get the Request Map wrapper, use RequestAware

public class MyAction implements RequestAware {
    private Map<String,Object> request;

    public void setRequest(Map<String,Object> request){ 
        this.request = request;
    }
}

To get the Session Map wrapper, use SessionAware

public class MyAction implements SessionAware {
    private Map<String,Object> session;

    public void setSession(Map<String,Object> session){ 
        this.session = session;
    }
}

To get the underlying HttpServletRequest and HttpSession objects, use ServletRequestAware:

public class MyAction implements ServletRequestAware {
    private javax.servlet.http.HttpServletRequest request;

    public void setServletRequest(javax.servlet.http.HttpServletRequest request){ 
        this.request = request;
    }

    public HttpSession getSession(){
        return request.getSession();
    }
}

That said, the standard data flow between JSP pages and Actions, or Actions and Actions, is obtained through Accessors / Mutators, better known as Getters and Setters. Don’t reinvent the wheel.

Leave a Comment