user
user

Reputation: 29

How to pass Action class variable value to another Action class in Struts 2?

How to pass Action class variable value to another Action class in Struts 2?

I want to use that variable value for the query in another action class.

Th logic is, I've used three properties in LoginAction class named email, username, password, and I am checking with the database values. After this I need the email property value to be retrieved in to the InboxAction Class. How can I do this?

Upvotes: -2

Views: 6431

Answers (3)

Jegatheesh M
Jegatheesh M

Reputation: 68

If you want to post all values to another action use 'chain', other wise use redirect-action and specify the parameters.

Upvotes: 0

Roman C
Roman C

Reputation: 1

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;
  }

} 

Upvotes: 3

Kartik73
Kartik73

Reputation: 513

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

Upvotes: 0

Related Questions