How to pass Action
class variable value into another Action
class in Struts 2?
I wanted to use that retrieved in the query variable in anot
There are different ways the actions could communicate with each other as well as they running in different threads and don't share the action context. The most popular way is to pass parameters with the request or in the URL and XWork converter will convert them to the action properties with the help of OGNL.
But I think the purpose of the LoginAction
is to authenticate the user by their credentials (email, username, password)
and save this information in the session map. It is a common resource that could be shared between actions. To get the session map available to the action and other actions they should implement the SessionAware
. It will help the Struts to inject the session map to the action property. If you want to use the session in many actions over the application then to not implement this interface in every action you could create a base 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 actions will extend the base action to get the session compability.
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 in the session and you could get the session from other action or JSP and user
object from the session
map.
public class InboxAction extends BaseAction {
@Override
public String execute() throws Exception {
User user = (User) getSession().get("user");
return SUCCESS;
}
}
Try this : use result type chain in the first action.
and add the name of the second action as a value to the result of the first action
link leads to the official page of the struts2 for the chain result
If you want to post all values to another action use 'chain', other wise use redirect-action and specify the parameters.