Data Encapsulation Mechanism in Struts2

Content from: Data Encapsulation Mechanism in Struts2

There are three mechanisms for data encapsulation in Struts2: attribute-driven, label-driven, and model-driven.

 

1. Attribute-driven
1. It is necessary to provide the set method of the corresponding attribute to encapsulate the data.
2. Which properties of the form need to encapsulate data, then provide the set method of the property in the corresponding Action class.
3. The data in the form is submitted, and finally the setXxx method in the Action class is found, and finally assigned to the global variable.

  • Note: The interceptor used by the Struts2 framework completes the data encapsulation.
  • Note: This method is not particularly good : because there are so many properties, there are so many set methods, and you need to manually store the data into the object.
  • Note: In this case, the Action class is equivalent to a JavaBean, which does not reflect the idea of ​​MVC . The Action class encapsulates data and receives request processing, so the coupling is high.

Specifically look at the implementation of an action:

public  class LoginActio extends ActionSupport{  
     // Action needs to process two data submitted by the form: username and password.  
    // The attribute value here should be consistent with the name value in the form  
     // and must have corresponding set and get methods   
   private String username; // consistent with the corresponding name of the form   
   private String password;  
   @Override  
   public execute()throws Exception{  
        System.out.println("username="+username);  
        System.out.println("password="+password);  
       return"success";  
   }  
   public String getUsername() {  
       return username;  
   }  
   publicvoid setUsername(String username) {  
       this.username= username;  
   }  
   public String getPassword() {  
       return password;  
   }  
   publicvoid setPassword(String password) {  
       this.password= password;  
   }  
}  

The form submission format is as follows:

<form action="LoginActio" method="post">  
    <input type="text" name="username">  
    <input type="text" name="password">  
    <button type="submit">提交</button>  
</form>  

 

After the configuration is complete, you can change the action attribute in the form in the form to the name of the current action (note that the suffix is ​​.action, or you can set it yourself, using the constant attribute). Then start the project and go to the corresponding page to enter the user name and password, and you can see that the relevant information has been printed in the console.

However, we have not done any related data encapsulation operations in the code, but the corresponding data has been encapsulated into properties.
This is the attribute encapsulation mechanism in the data encapsulation of struts2. You only need to set the attributes of the data to be submitted in the current form in the Action (note that there may be a problem of attribute type conversion here, this example only involves attributes of type String, At the same time, the data submitted in the form is also of type String. All does not involve type conversion issues) When the form is submitted, the data will be directly encapsulated into the corresponding attributes. In fact, this is achieved through the reflection mechanism of java.

 

2. Tag-driven
data can be encapsulated by using OGNL expressions on the page. The premise of realizing automatic encapsulation of form data through tags in Struts2 is to add Struts2 tag support to the form.

<%@taglib prefix="s" uri="/struts-tags" %>

1. Use OGNL expression to encapsulate data in the page, you can directly encapsulate the attribute into a certain JavaBean object.
2. Define a JavaBean in the page and provide a set method: for example: private User user;
3. The writing in the page has changed, and the OGNL method needs to be used. The writing method in the form: <input type="text" name= "user.username">

  • Note: It is not enough to provide only one set method. If there is no user instantiation, you must also provide the get and set methods of the user attribute. First call the get method to determine whether there is an instance object of the user object. If not, call the set method to The object created by the interceptor is injected in.

Specific Action examples are as follows:

/** 
 * Dynamic parameter encapsulation: attribute-driven
 * OGNL
 * All encapsulated dynamic parameter operations: are encapsulated by an interceptor called params.
 */  
public class TestAction extends ActionSupport {  
  
  
    private User user = new User(); // User is an encapsulated javaBean model  
  
  
    public String execute(){  
        System.out.println("name is "+user.getName()+" and age is "+user.getAge());  
        return SUCCESS;  
    }  
  
  
    public User getUser() {  
        System.out.println("getUser");  
        return user;  
    }  
  
  
    public void setUser(User user) {  
        System.out.println("setUser");  
        this.user = user;  
    }  
}  

The form is submitted as follows:

<% -- dynamic parameter encapsulation: object navigation mapping   
        At this point, the value of the name attribute of the form element is no longer an ordinary string.  
        but an OGNL expression.  
        OGNL:Object Graphic Navigationg Language  
               Object Graph Navigation Language  
    --%>  
    <form action="${pageContext.request.contextPath}/testAction.action" method="post">  
        用户名:<input type="text" name="user.name"/><br/>  
        年龄:<input type="text" name="user.age"/><br/>  
        <input type="submit" value="提交"/>  
    </form>  

You can also use struts2 tags:

<% -- The way to locate action here is similar to configuring struts.xml, using namespace and action name -- %>   
< s:form namespace = "/normal" action = "testAction.action" method = "POST" >   
    < % -- The name attribute must also be written like this -- %>   
    < s:textfield name ="user.name" />   
    < s:password name ="user.passwd" />   
    < s:submit > submit </ s:submit >   
</ s:form >  

 

3. Model-driven.
Using the model-driven approach, the data in the form can also be directly encapsulated into a JavaBean object, and the form's writing method is no different from the previous writing method ! The written page does not need any changes, and the value of the name attribute is written normally.
Model-driven writing steps
* Manually instantiate JavaBean, namely: private User user = new User();
* The corresponding Action must implement the ModelDriven<T> interface, implement the getModel() method, and return user in the getModel() method Can! !

Let's look at an Action example:

// Implement the ModelDriven interface, and the generic type writes our encapsulated data, that is, the javaBean object we wrote ourselves User   
public  class StudentAction extends ActionSupport implements ModelDriven<User> {  
     // We must instantiate our encapsulated data, struts2 will directly Use our class to set the data in  
     // so we have to write get and set methods in this class   
    private User u = new User(); // instantiate javaBean  
  
  
    // The method that must be implemented to implement this interface returns the data we encapsulated, that is, the javaBean object   
    @Override  
     public User getModel() {  
         return u;  
    }  
  
  
    @Override  
    // We haven't set anything in this method, but struts2 still puts the data in for us  
     // This is actually the application of java reflection   
    public String execute() throws Exception {  
        System.out.println(u.getName());  
        System.out.println(u.getPasswd());  
        return "success";  
    }  
}  

The form submission method is exactly the same as the first attribute-driven method, and no changes are required.

The general principle of the above method is as follows:
* Before the request is sent to the action, call the getModel method in our custom Action class to obtain the javaBean object that encapsulates the form data
* After obtaining the object, we can obtain the corresponding class type 
* The list of attributes in the class can be obtained by reflection 
* The list of names in the form can be obtained by request.getParameterNames() 
* Determine the name value and the attribute name. If they are consistent, the set method of the attribute is called by reflection to set the corresponding attribute value. Parameters 
* Finally complete the encapsulation of the completed data 

 

4. Action’s encapsulation of collection objects
1. Encapsulate data into Collection
Because the Collection interface will have subscript values, there will be some differences in the writing of all pages. Note:
<input type="text" name="products[0] .name" />
is written in Action, you need to provide a collection of products, and provide get and set methods

2. Encapsulate data into Map
Map collection is in the form of key-value pairs, and the page is written
<input type="text" name="map['one'].name" />
Action provides map collection, and provides get and set methods.

**A model-driven approach to encapsulating data into collections is not recommended in Actions.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324956261&siteId=291194637