0

I am new to Struts2 and I just realized that whenever I call an action class via a form of a JSP page, I need to have getters and setters for all the parameters in the called action class to access the parameters as shown in below action class:

public class LoginAction extends ActionSupport {

    private String userName;
    private String password;

    public String execute {
    System.out.println(this.userName+" "+this.password);
    return "success";
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

However, I also have a POJO class for User which has the same 2 attributes and its getters and setters. Is there a way I can use those getters/setters within my action class? Right now I have getters and setters in both my POJO and my action class. Can anyone help how to eliminate this redundancy?

Roman C
  • 49,761
  • 33
  • 66
  • 176
Crusaderpyro
  • 2,163
  • 5
  • 29
  • 53

1 Answers1

2

The action bean are put on the top of the value stack, the parameters are accessed directly by name, i.e. userName, password. Struts2 uses OGNL to access objects in the value stack, so if you place your POJO to the value stack it will be accessible via OGNL. For example

public class LoginAction extends ActionSupport {

   private User user;

   public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

it should use parameter names user.userName and user.password.

Roman C
  • 49,761
  • 33
  • 66
  • 176
  • Thanks for the quick answer. Also in this case I have 2 attributes - username and password. In the case where I am sending just username as a part of the form, again I should use the POJO getter setter as you mentioned or just a separate getter setter for username in my action class ? – Crusaderpyro Mar 20 '14 at 09:38
  • 1
    You should use OGNL notation to access bean properties. The dot allows to reference nested bean's properties. If you don't access nested bean's properties but access action class bean from the top of the value stack then you access them by name. – Roman C Mar 20 '14 at 09:50