How to pass the value of an Action class variable to another Action class in Struts 2
There are different ways of interaction of actions with each other, as well as working in different threads and not separating the context of actions. The most popular way is to pass parameters with a request or in a URL, and the XWork converter converts them to action properties using OGNL.
But I think the goal LoginAction
is to authenticate the user by their credentials (email, username, password)
and store that information in the session map. It is a shared resource that can be shared across activities. In order to access the session map for an action and other actions, they must implement SessionAware
. This will help Struts insert the session map into the action property. If you want to use a session in many actions on your application, so as not to implement this interface in every action, you could create a basic action.
public class BaseAction extends ActionSupport implements SessionAware {
private Map<String, Object> session;
public setSession(Map<String, Object> session){
this.session = session;
}
public Map<String, Object> getSession(){
return session;
}
}
then the actions will extend the base action to get session compatibility.
public class LoginAction extends BaseAction {
@Override
public String execute() throws Exception {
User user = getUserService().findBy(username, email, password);
getSession().put("user", user);
return SUCCESS;
}
}
Now the user is in session and you can get the session from another activity or JSP and user
object from the map session
.
public class InboxAction extends BaseAction {
@Override
public String execute() throws Exception {
User user = (User) getSession().get("user");
return SUCCESS;
}
}
source to share