Three methods for receiving parameters for action:
1. Use the property of action to receive parameters:
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? Name = magci & age = 18;
Eg:
Public class useraction extends actionsupport {
Private string name;
Private int age;
Public String add (){
System. Out. println ("name =" + name );
System. Out. println ("age =" + age );
Return success;
}
Public String getname (){
Return name;
}
Public void setname (string name ){
This. Name = Name;
}
Public int getage (){
Return age;
}
Public void setage (INT age ){
This. Age = age;
}
}
2. Use domainmodel to receive parameters:
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. Name = MGC & User. Age = 18;
Import user. model. user;
Import com. opensymphony. xwork2.actionsupport;
Public class useraction extends actionsupport {
Private user;
// Private userdto;
Public String add (){
System. Out. println ("name =" + User. getname ());
System. Out. println ("age =" + User. getage ());
Return success;
}
Public user getuser (){
Return user;
}
Public void setuser (User user ){
This. User = user;
}
}
If the number of passed parameters does not match the number of model attributes, we generally use DTO as the intermediate layer for data transmission.
3. Use modeldriven to receive parameters:
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. getname ();
C. Send: directly use the property name to pass the parameter, for example, user2! ADD? Name = MGC & age = 18
Eg:
Import struts2.user. model. user;
Import com. opensymphony. xwork2.actionsupport;
Import com. opensymphony. xwork2.modeldriven;
Public class useraction extends actionsupport implements modeldriven <user> {
Private user = new user ();
Public String add (){
System. Out. println ("name =" + User. getname ());
System. Out. println ("age =" + User. getage ());
Return success;
}
@ Override
Public user GetModel (){
Return user;
}
}
Execution Process: first create an action. Check whether the modeldriven interface is implemented, then call getmodol () to return a modol object from the action. Then, call the set attribute of the modol object. In this way, you can receive the passed parameters.