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

后端 未结 3 1343
日久生厌
日久生厌 2020-12-22 13:52

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

3条回答
  •  春和景丽
    2020-12-22 14:13

    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 session;
    
      public setSession(Map session){
        this.session = session;
      }
    
      public Map 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;
      }
    
    } 
    

提交回复
热议问题