Struts (4) of SSH framework -- simple use of Struts to check for missing BeanUtils
1) Background
In the previous blog, we mentioned an important javaBean tool-BeanUtils. This blog briefly introduces BeanUtils. As a third-party service, BeanUtils provides various operations for javaBean.
Its main functions are summarized as follows:
1. Use BeanUtils. cloneBean () to clone a JavaBean instance
2. Using BeanUtils. copyProperties () to replicate attributes between javebeans
3. Use BeanUtils. setProperty () to set properties for a JavaBean instance
4. Read related information from the JavaBean instance through BeanUtils. getProperty
2) specific practices:
public class User {private String userNameString;private String userPasswordString;public String getUserNameString() {return userNameString;}public void setUserNameString(String userNameString) {this.userNameString = userNameString;}public String getUserPasswordString() {return userPasswordString;}public void setUserPasswordString(String userPasswordString) {this.userPasswordString = userPasswordString;}}
1) clone an object
User nUser=new User();User suser=(User)BeanUtils.cloneBean(nUser);
If you are interested, check whether suser and nuser are in the same instance? That is to say, is the cloned BeanUtils pointing to the same instance?
2) Copying Properties
JavaBean with the same attributes can be copied through BeanUtils. In Struts1, the object obtains the value in ActionForm.
Traditional method:
// Obtain the ActionForm data UserActionForm uForm = (UserActionForm) form; User user = new User (); // assign values to users one by one. setUsername (uForm. getUsername); user. setPassword (uForm. getPassword); user. setAge (uForm. getAge );
There are few attributes, so assigning values one by one is understandable. However, if there are more attributes, It is troublesome to assign values to multiple attributes one by one.
After using BeanUtils
// After BeanUtils is used, UserActionForm uForm = (UserActionForm) form; User user = new User (); // attribute copy value: BeanUtils. copyProperties (user, uForm );
A simple BeanUtils. copyProperties (user, uForm); then, all the UForm attribute values are assigned to the user.
3) Get and SetProperty
Assign values to object attributes dynamically through get and set.
// Assign BeanUtils to an object attribute. setProperty (nUser, "UserNameString", "leilei"); // get the BeanUtils attribute value of an object. getProperty (nUser, "UserNameString"); BeanUtils converts strings to the true type of Bean attributes using the ConvertUtils class, facilitating bean extraction from objects such as HttpServletRequest or bean output to the page. PropertyUtils retains the original Bean type.
Iii) Summary
BeanUtils is a third-party service that provides operations for the JavaBean method. In struts1, BeanUtils is used to convert and assign values to attribute values. (BeanUtils. populate (bean, properties); here, it mainly extends other functions and advantages of BeanUtils.