3

I load object userData like below, to show it on JSP. (later it will be loaded from database) using Register() method type GET.

Next I fill another fields of userData on JSP and click register.

Then method Register() start again, but not use this same RegistrationAction.

So e.g. attribute1 will be still 1 instead of 2.

Sample:

public class RegistrationAction extends ActionSupport{
       int attribute1=0;
       public String Register() throws Exception {
           attribute1++;
           if(request.getMethod().equals("GET")){  //load object to form
              user=new UserData();
              user.setName("lucas");
               return NONE;
           } 
            //else POST -> save()
      }
}

So what I should do to start this same instance of action ?

Roman C
  • 49,761
  • 33
  • 66
  • 176
lucas999
  • 169
  • 1
  • 2
  • 11
  • [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) to its maximum, IMHO. Please define what you *really* need to do, that, I'm confident, won't involve accessing the same instance of a ThreadLocal, disposable action. If you need to remember values across multiple calls, the Session is your friend – Andrea Ligios Apr 14 '16 at 20:30
  • 1
    New request = new action instance. Store the data somewhere or pass it to new request. – Aleksandr M Apr 15 '16 at 07:42
  • I would also suggest you to use the session attributes for this requirement. – Mohan Apr 15 '16 at 10:40
  • You need to out it in session, may be this plugin can also help you http://code.google.com/p/struts2-conversation/ – Alireza Fattahi Apr 16 '16 at 04:36

1 Answers1

3

You shouldn't start the same instance. The same instance won't be thread-safe.

Each request make a new action instance, and you have to initialize it before the result view.

You can do it with Preparable.

Having three actions that share a data between calls requires preparing a model using Preparable to populate fields from session or use a session object reference to provide default values for fields to keep them saved.

public class RegistrationAction extends ActionSupport implements Preparable, SessionAware {

  public void prepare() {
     user=new UserData();
     user.setName("lucas");
     attribute1 = session.get("attribute1");
  }

  private Map<String, Object> session;

  @Override
  public void setSession(Map<String, Object> session) {
     this.session = session;
  } 

   int attribute1=0;
   public String Register() throws Exception {
       attribute1++;
       session.put("attribute1", attribute1);
       if(request.getMethod().equals("GET")){  //load object to form          
           return SUCCESS;
       } 
        //else POST -> save()
    }
}
Roman C
  • 49,761
  • 33
  • 66
  • 176