In Struts2, three methods are used to receive parameters for an Action:
1. Use the property of Action to receive parameters: (driven by property)
A. Definition: Define attributes in the Action class and create get and set methods;
B. Receive: receive parameters through properties, such as userName;
C. Send: use the property name to pass parameters, for example, user1! Add? UserName = Magci;
JSP:
Action: directly obtained through the get and set methods.
Public class sysAction extends ActionSupport {
Private String username;
Public String login () throws Exception {
System. out. println (username );
Return SUCCESS;
}
Public String getUsername (){
Return username;
}
Public void setUsername (String username ){
This. username = username;
}
}
2. Use ModelDriven to receive parameters: (the model-driven method must implement ModelDriven. Interface. The second method is inconvenient to pass in multiple models)
A. Definition: Action implements the ModelDriven generic interface, defines the object of the Model class (must be new), and returns the object through the getModel method;
B. Receive: parameters are received through object attributes, such as user. getUserName ();
C. Send: directly use the property name to pass the parameter, for example, user2! Add? UserName = MGC
JSP:
Action: The getModel () method must be implemented.
Public class sysAction extends ActionSupport implements ModelDriven {
Private User user;
Public String login () throws Exception {
System. out. println (getModel (). getUsername ());
Return SUCCESS;
}
Public User getModel (){
If (null = user ){
Return user = new User ();
}
Return user;
}
}
3. Use DomainModel to receive parameters: (the third method of domain model does not implement ModelDriven. You can also use attributes of multiple model objects .)
A. Define: Define the Model class. In the Action, define the object of the Model class (new is not required) and create the get and set methods of the object;
B. Receive: parameters are received through object attributes, such as user. getUserName ();
C. Send: Use the object property to pass parameters, such as user2! Add? User. userName = MGC;
JSP:
Action: The set method must be provided.
Public class sysAction extends ActionSupport {
Private User user;
Private Teacher teacher;
Public String login () throws Exception {
System. out. println (user. getUsername ());
System. out. println (teacher. getLevel ());
Return SUCCESS;
}
Public void setUser (User user ){
This. user = user;
}
Public void setTeacher (Teacher teacher ){
This. teacher = teacher;
}
}