HOW TO ACCESS SESSION IN STRUTS 2 WITH EXAMPLE


Some of my friends are confused, how to deal with session in struts2, because struts 2 is Servlet API independent. We will try to understand all possible way to deal with session.

You can obtain the session attributes by asking the ActionContext or implementing SessionAware. Implementing SessionAware is preferred.

Using ActionContext:

getContext()  static method of ActionContext return instance of ActionContext, on which getSession() method  is called which return Map of HttpSession value.

Map attmap = ActionContext.getContext().getSession();

Now get(), put() and remove() method of Map is used for getting, putting and removing attribute in session scope.


Example: how to login and logout

public String execute() throws Exception {

        if ("admin".equals(userId) && "password".equals(passwd)) {

                                Map session = ActionContext.getContext().getSession();

                                session.put("logined","true");

                                return SUCCESS;

        }

        return ERROR;

    }

    public String logout() throws Exception {

                Map session = ActionContext.getContext().getSession();

                session.remove("logined");

      return SUCCESS;

    }

}

Implementing SessionAware:

To provide loosely coupled system, struts use a technique called dependency injection or inversion of control. Struts provide SessionAware interface with setter method to inject session attribute in Action class. SessionAware interface must implemented by Action class to deal with session scope object. It contain only one method setSessionMap(Map<String,Object> map), which set SessionMap for Action.

Actually, SessionMap class provide several method to deal with HttpSession

Some important methods are:

public Object put(Object key, Object value) : store object in session scope

public Object get(Object key) : get object form session scope

public Object remove(Object key) : remove object from session scope

public void invalidate() : invalidate session

Example: how to login and logout

public class LoginAction extends ActionSupport implements SessionAware{

    private SessionMap<String,Object> sessionMap;

//SessionMap object is injected by struts 2

    public void setSession(Map<String, Object> map) {

         sessionMap = (SessionMap<String, Object>) map;

    }

    public String execute() throws Exception {

        if ("admin".equals(userId) && "password".equals(passwd)) {

                                sessionMap.put("logined","true");

                                return SUCCESS;

        }

        return ERROR;

    }

    public String logout() throws Exception {

                if(sessionMap!=null){

                sessionMap.invalidate();

}

      return SUCCESS;

    }

}

No comments:

Post a Comment